1

I have a spring bean Lets us say BeanA and scope is default injected via constructor.I have instance variable c which i am not using and its getting used in method1 and method2.Note that C is not injected.But in multithreaded environment I am facing issues because of variable C .As i unserstand default scope is singleton so this should work? The issues are like when diffrent users are trying to access the bean at same time They are getting stale instance of c Like example let user 1 instantiate c = hello .user 2 is seeing same hello.I want to understand how instance variable behave if not injected and used in diffrent methods?

class BeanA{
private A a,
private B b;
private C c;

public BeanA( A a, B b){

this.a=a;
this.b=b;
}

public method1(){
 c= //assignSomething
}

public method2(){
 c= //assignSomethingElse
}

}
7
  • What issues? It's unclear to me what your scenario is. Commented Dec 3, 2014 at 3:45
  • What kind of issue ? it still vague. Commented Dec 3, 2014 at 3:46
  • Updates sorry for the inconvience Commented Dec 3, 2014 at 3:53
  • What makes you think the bean being a Singleton would help? It sounds like you need to brush up on background knowledge. This question is not phrased in a way that can be answered more effectively then "it's doing exactly what it should, you need to figure out why that's not what you want" Commented Dec 3, 2014 at 3:58
  • Sounds like you need to add synchronized keyword for both methods. Otherwise race condition can happen. Singleton does not guarantee thread safety. Commented Dec 3, 2014 at 4:06

1 Answer 1

2

As you have only one instance of Bean A , all the users will be sharing same object. This will result in having only one variable C being used by all threads . So value of C is being shared between threads. This is the expected behavior.

It has nothing to with Spring injection. Its basic of java language itself. If you need different instance of BeanA,then you need to define its scope to request (in case of webapplicaton) or prototype as per your need.

It will be really helpful, if you state what you are trying to acheive.

Sign up to request clarification or add additional context in comments.

1 Comment

Be aware that setting the scope to prototype is only effective if you ask the Spring context to supply the bean. I've seen a lot of code where the author thought prototype bestowed some miraculous behavior that cured all their threading issues!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.