• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Are spring beans thread-safe?

 
Sagar Kale
Ranch Hand
Posts: 188
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I don't have experience on Spring. I have just learned basic. I wanted to know if Spring bean with default scope are thread safe. If not then what is good option to use them in multi threaded environment 1) to define scope as prototype or 2) defining synchronized method.
 
Hong Anderson
Ranch Hand
Posts: 1936
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Spring beans are not thread-safe.
 
Sagar Kale
Ranch Hand
Posts: 188
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks for reply.

Now what is good option to use them in multi threaded environment 1) to define scope as prototype or 2) defining synchronized method.
 
Hong Anderson
Ranch Hand
Posts: 1936
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I don't get defining as prototype will help in that way?

There are several methods to make code thread-safe, such as using ThreadLocal, synchronize codes.
 
Sagar Kale
Ranch Hand
Posts: 188
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I am talking from web application prospective, when multiple request comes and same spring bean is accessed. If scope is prototype, new instance will be created. ( Assuming there are not many concurrent users but there are few lets say 15)
 
Hong Anderson
Ranch Hand
Posts: 1936
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
For stateful beans, scope should be prototype, but beware that if you inject prototype beans into singleton beans, the prototype beans will get created only once per the singleton beans instance.
If you want they to get created multiples time, you have to use Method Injection.

Please read http://static.springframework.org/spring/docs/2.0.x/reference/beans.html#beans-factory-method-injection for more detail.
 
Sagar Kale
Ranch Hand
Posts: 188
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Kengkaj
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic