Results 1 to 3 of 3

Thread: Are methods in singleton class thread safe?

  1. #1
    Join Date
    Oct 2010
    Posts
    1

    Default 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. #2
    Join Date
    Oct 2010
    Posts
    1

    Default

    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. #3
    Join Date
    Jun 2006
    Location
    The Netherlands
    Posts
    13,632

    Default

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

Tags for this Thread

Posting Permissions

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