Solved

Java multi thread singleton

Posted on 2010-09-13
21
794 Views
Last Modified: 2012-05-10
I just want to confirm since singleton only has one instance, it is guranteed that my business logic method could be executed as thread safe. Am I right?
public class SingletonTest{

   private static SingletonTest instance = new SingletonTest();



   private SingletonTest{

     ****

   }  



   public static SingletonTest getInstance(){

               return instance;          

   }  



   public void SomebusinessLogicMethod(){

      /*  Ha, I am going to access some shared resources */

   }  

}

Open in new window

0
Comment
Question by:JianJunShen
  • 5
  • 4
  • 4
  • +4
21 Comments
 
LVL 40

Assisted Solution

by:gurvinder372
gurvinder372 earned 135 total points
ID: 33669363
Singleton pattern ensures that you have only one object/resource.
You can implement thread safe behavior by using synchronized methods and synchronized blocks
some good reads
http://www.ibm.com/developerworks/java/library/j-dcl.html
http://java.sun.com/developer/technicalArticles/Programming/singletons/
0
 
LVL 65

Expert Comment

by:rockiroads
ID: 33669373
if you make the getInstance synchronized that would help make it thread safe I think

public static SingletonTest getInstance() {
    if( instance == null ) {
      synchronized( SingletonTest.class ) {
        if ( instance == null ) {
           instance = new SingletonTest();
        }
      }


0
 
LVL 92

Assisted Solution

by:objects
objects earned 45 total points
ID: 33669508
depends on the environment you are running it in. for example if its a webapp then there could well be more than one instance.

Also that code is not thread safe
0
 
LVL 16

Assisted Solution

by:Valeri
Valeri earned 182 total points
ID: 33669535
If you need only confirmation whether your class is thread safe, the answer is YES.
The implementation you have posted implements singleton pattern and it's thread safe!
0
 
LVL 16

Assisted Solution

by:Valeri
Valeri earned 182 total points
ID: 33669557
objects why do you think it's not thread safe? Java static initializers are thread safe, and getInstance() don't need to be synchronized.
0
 
LVL 40

Assisted Solution

by:gurvinder372
gurvinder372 earned 135 total points
ID: 33669567
@Valeri: not answering on Objects behalf, but you can check the first link that i have posted in my reply to see why it is not thread safe
0
 
LVL 16

Expert Comment

by:Valeri
ID: 33669606
@gurvinder372 The authors implementation is different. He has avoided lazy initialization of the instance object. this kind of initialization is thread safe :
private static SingletonTest instance = new SingletonTest();
0
 
LVL 92

Expert Comment

by:objects
ID: 33669640
access to SomebusinessLogicMethod() needs to be synchronized
0
 
LVL 40

Assisted Solution

by:gurvinder372
gurvinder372 earned 135 total points
ID: 33669664
@Valeri: that is correct, the object created will be only one, but it can still be accessed by multiple threads.
So other methods needs to be synchronized.
0
 
LVL 26

Accepted Solution

by:
ksivananth earned 92 total points
ID: 33669668
>>The authors implementation is different

true, its thread safe.

But in webapp env, we may not assume that there will be only one instance created because there can be multiple classloader which will cause multiple instance though it is static. if you try to load same class through two different classloader, there will be two instance of the same class created because a class loaded by diff classloader is not treated equally.
0
Do You Know the 4 Main Threat Actor Types?

Do you know the main threat actor types? Most attackers fall into one of four categories, each with their own favored tactics, techniques, and procedures.

 
LVL 16

Assisted Solution

by:Valeri
Valeri earned 182 total points
ID: 33669748
Synchronization of SomebusinessLogicMethod is not needed, only access to the shared resources is needed.
>> So other methods needs to be synchronized.
getInstance() don't need to be syncronized.

0
 
LVL 16

Assisted Solution

by:Valeri
Valeri earned 182 total points
ID: 33670094
About the environment with multiple class loaders I absolutely agree with ksivananth and objects.
0
 

Author Comment

by:JianJunShen
ID: 33670184
I summarize answer here: my example of creating instance is thread safe, but business logic method is not thread safe. Am I right? If I am right, I will close this question.
0
 
LVL 10

Assisted Solution

by:Hegemon
Hegemon earned 46 total points
ID: 33670197
Your singleton guarantees that the business method will be invoked on the only instance of this class (per classloader), nothing more. The method itself is NOT thread safe, it is an ordinary method. To make it thread safe, access to shared resources must be synchronized. Either the whole method can be declared as synchronized or a block of code inside it.
0
 
LVL 26

Assisted Solution

by:ksivananth
ksivananth earned 92 total points
ID: 33670204
>>Am I right?

yes, if its loaded through single classloader
0
 

Author Closing Comment

by:JianJunShen
ID: 33670247
I did not give Rockiroads points is because it is not documented as thread safe in some Java memeory model. Please refer to gurvinder372 thread.
0
 
LVL 65

Expert Comment

by:rockiroads
ID: 33679217
yea okay. I just gave a simple example based on your code about using synchronise. I am aware that you can have multiple copies. Problem with the way I suggested would mean you need to sync all access to the variable that could be written by multiple threads. That goes some way towards making it thread safe but probably not so elegant way of doing things.
Then again I could be wrong but that is what I have been led to believe.
0
 
LVL 26

Expert Comment

by:ksivananth
ID: 33679456
>>That goes some way towards making it thread safe but probably not so elegant way of doing things.
 
actually its not 100% safe, it will encounter the DCL( double checked locking ) issue
0
 
LVL 65

Expert Comment

by:rockiroads
ID: 33683633
so if everything is synchronized, dcl would be an issue? well maybe but I read it different from here
http://www.javaworld.com/javaworld/jw-02-2001/jw-0209-double.html?page=4

The most effective way to fix the DCL idiom is to avoid it. The simplest way to avoid it, of course, is to use synchronization. Whenever a variable written by one thread is being read by another, you should use synchronization to guarantee that modifications are visible to other threads in a predictable manner.



0
 
LVL 26

Expert Comment

by:ksivananth
ID: 33688940
>>so if everything is synchronized, dcl would be an issue?

no, if the entire method is sync'ed, it would be thread safe but in your comment, you were checking null and then sync'ed which will cause DCL
0
 
LVL 65

Expert Comment

by:rockiroads
ID: 33691890
ah, didnt see that. the instance null check done after as well, not sure why I did 2, anyways, thanks for that spot.
0

Featured Post

Highfive + Dolby Voice = No More Audio Complaints!

Poor audio quality is one of the top reasons people don’t use video conferencing. Get the crispest, clearest audio powered by Dolby Voice in every meeting. Highfive and Dolby Voice deliver the best video conferencing and audio experience for every meeting and every room.

Join & Write a Comment

Suggested Solutions

An old method to applying the Singleton pattern in your Java code is to check if a static instance, defined in the same class that needs to be instantiated once and only once, is null and then create a new instance; otherwise, the pre-existing insta…
Java had always been an easily readable and understandable language.  Some relatively recent changes in the language seem to be changing this pretty fast, and anyone that had not seen any Java code for the last 5 years will possibly have issues unde…
Viewers will learn about the different types of variables in Java and how to declare them. Decide the type of variable desired: Put the keyword corresponding to the type of variable in front of the variable name: Use the equal sign to assign a v…
Viewers will learn how to properly install Eclipse with the necessary JDK, and will take a look at an introductory Java program. Download Eclipse installation zip file: Extract files from zip file: Download and install JDK 8: Open Eclipse and …

747 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

10 Experts available now in Live!

Get 1:1 Help Now