This week's book giveaway is in the Servlets forum.
We're giving away four copies of Murach's Java Servlets and JSP and have Joel Murach on-line!
See this thread for details.
The moose likes Spring and the fly likes Are spring beans thread-safe? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Frameworks » Spring
Bookmark "Are spring beans thread-safe?" Watch "Are spring beans thread-safe?" New topic
Author

Are spring beans thread-safe?

Sagar Kale
Ranch Hand

Joined: May 02, 2008
Posts: 188
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

Joined: Jul 05, 2005
Posts: 1936
Spring beans are not thread-safe.


SCJA 1.0, SCJP 1.4, SCWCD 1.4, SCBCD 1.3, SCJP 5.0, SCEA 5, SCBCD 5; OCUP - Fundamental, Intermediate and Advanced; IBM Certified Solution Designer - OOAD, vUML 2; SpringSource Certified Spring Professional
Sagar Kale
Ranch Hand

Joined: May 02, 2008
Posts: 188
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

Joined: Jul 05, 2005
Posts: 1936
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

Joined: May 02, 2008
Posts: 188
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

Joined: Jul 05, 2005
Posts: 1936
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

Joined: May 02, 2008
Posts: 188
Thanks Kengkaj
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Are spring beans thread-safe?
 
Similar Threads
MVC Pattern doubt
are request attributes and session attributes thread safe?
question about action class
Spring singleton Beanscope
Are implicit objects in JSP are thread safe???