Announcement Announcement Module
No announcement yet.
Basic question on Thread safety via singleton beans Page Title Module
Move Remove Collapse
Conversation Detail Module
  • Filter
  • Time
  • Show
Clear All
new posts

  • Basic question on Thread safety via singleton beans

    Hello All,

    We know that by default Spring manages singleton beans instead of prototype and we can change this configuration. But considering that we are using only Singleton beans, how thread safety is managed by Spring when handling concurrent requests to the same bean instance.

    I have this question as in my recent projects, I noticed all beans were configured as singleton in a very large scale enterprise application consiting of multiple tiers. So we get several concurrent requests that needs to be handled and none of the methods of those beans are actually are Synchronized (Synchronize keyword or block). So for instance, for a class say

    Class A{
    public void method(){

    being invoked concurrently, how would Spring manage the Thread safety. If Spring does not manage it, and it would be the responsibility of the user, then is my project in a big flaw, as we do not synchronize the calls. Is changing the scope to prototype a feasible option from design perspective.

    Per recommendations, which one is suitable Singleton or prototype and which one is widely used at enterprise levels.


  • #2
    There is no easy answer. Both singletons and prototypes are used in real software. There is no magic in thread-safety. If you need to synchronize, or you need prototypes, then do it. Don't assume you need a single solution in every case.


    • #3
      Does the ThreadScope help?


      • #4
        Please use the search as this question has been answered numerous times before!

        In short in general there is no issue with using a singleton as long as it doesn't keep instance state. So as long as you don't have variables on the class level which represent state for that object there is nothing wrong with your setup ( in general you shouldn't keep state in your services, controllers). I also suggest you do a little more research on singletons and thread safety, enough has been written on the subject.