Results 1 to 4 of 4

Thread: Basic question on Thread safety via singleton beans

  1. #1

    Default 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.

    Thanks

  2. #2
    Join Date
    Jan 2006
    Location
    Seattle, Washington
    Posts
    467

    Default

    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. #3
    Join Date
    Jul 2010
    Posts
    139

    Default

    Does the ThreadScope help?

  4. #4
    Join Date
    Jun 2006
    Location
    The Netherlands
    Posts
    13,624

    Default

    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.
    Marten Deinum
    Java Consultant / Pragmatist / Open Source Enthousiast / Author


    Pro Spring MVC: With Web Flow
    Conspect

    Have you read the reference guide.
    Use the [ code ] tags, young padawan

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •