Solved

Java multi thread singleton

Posted on 2010-09-13
21
799 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
Free Tool: Path Explorer

An intuitive utility to help find the CSS path to UI elements on a webpage. These paths are used frequently in a variety of front-end development and QA automation tasks.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

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

Free Tool: Path Explorer

An intuitive utility to help find the CSS path to UI elements on a webpage. These paths are used frequently in a variety of front-end development and QA automation tasks.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
null output 3 35
How do I remove an object from a 3 40
Facing this issue for maven proxy setting 2 20
Eclipse Java import and method not resolved 4 48
By the end of 1980s, object oriented programming using languages like C++, Simula69 and ObjectPascal gained momentum. It looked like programmers finally found the perfect language. C++ successfully combined the object oriented principles of Simula w…
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…
Video by: Michael
Viewers learn about how to reduce the potential repetitiveness of coding in main by developing methods to perform specific tasks for their program. Additionally, objects are introduced for the purpose of learning how to call methods in Java. Define …
Viewers will learn about basic arrays, how to declare them, and how to use them. Introduction and definition: Declare an array and cover the syntax of declaring them: Initialize every index in the created array: Example/Features of a basic arr…

860 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