Announcement Announcement Module
No announcement yet.
Are methods in singleton class thread safe? Page Title Module
Move Remove Collapse
Conversation Detail Module
  • Filter
  • Time
  • Show
Clear All
new posts

  • Are methods in singleton class thread safe?

    Is Concurrent method access in singleton class thread safe?

    I am using Spring framework (MVC) with the default scope as Singleton.

    For example, if the controller of my web application is a Singleton class, are the methods declared to access Model/Business/DB classes thread safe, if accessed by multiple threads at the same time? How about calls to DB for database access/update from these methods in the Controller?

    Need guidance and I aprreciate any help/suggestions for this issue.

  • #2
    Singleton class methods are not thread safe unless it is synchronized.

    It is not a good to have thread safe code in the model/service/dao to provide service concurrently. Method in these layers should take data transfer object or wrapper objects as parameters and do the job. It is good to maintain these service methods as stateless by keeping the temporary variable within the method scope.

    If you have any thread safe data (like cache) need to be accessed within these layers use synchronized (it affects the performance in multithreaded application)


    • #3
      I suggest a good read on java concurrency and thread safty for both of you.

      If you use shared data (like instance variables) and modify it then your method isn't thread safe. If you don't do this and only have member variables (inside the method body) then there is no problem (no need for synchronized).