Solved

Java multi thread singleton

Posted on 2010-09-13
21
802 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 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
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
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

Get 15 Days FREE Full-Featured Trial

Benefit from a mission critical IT monitoring with Monitis Premium or get it FREE for your entry level monitoring needs.
-Over 200,000 users
-More than 300,000 websites monitored
-Used in 197 countries
-Recommended by 98% of users

Question has a verified solution.

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

After being asked a question last year, I went into one of my moods where I did some research and code just for the fun and learning of it all.  Subsequently, from this journey, I put together this article on "Range Searching Using Visual Basic.NET …
Java functions are among the best things for programmers to work with as Java sites can be very easy to read and prepare. Java especially simplifies many processes in the coding industry as it helps integrate many forms of technology and different d…
Viewers learn about the “while” loop and how to utilize it correctly in Java. Additionally, viewers begin exploring how to include conditional statements within a while loop and avoid an endless loop. Define While Loop: Basic Example: Explanatio…
Viewers learn about the scanner class in this video and are introduced to receiving user input for their programs. Additionally, objects, conditional statements, and loops are used to help reinforce the concepts. Introduce Scanner class: Importing…

626 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