This week's book giveaway is in the OCPJP forum.
We're giving away four copies of OCA/OCP Java SE 7 Programmer I & II Study Guide and have Kathy Sierra & Bert Bates on-line!
See this thread for details.
The moose likes OO, Patterns, UML and Refactoring and the fly likes singleton with lazy initialization Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of OCA/OCP Java SE 7 Programmer I & II Study Guide this week in the OCPJP forum!
JavaRanch » Java Forums » Engineering » OO, Patterns, UML and Refactoring
Bookmark "singleton with lazy initialization" Watch "singleton with lazy initialization" New topic
Author

singleton with lazy initialization

Max White
Ranch Hand

Joined: Jun 28, 2008
Posts: 85
Hi ,
I have the following doubt in the singleton pattern.

Kindly ignore the typing errors in the above code.The point at issue is, if we write the code as I did above, it results in double-checked locking.
So, if I change the code as shown below, would it be correct & free from double-checked locking?


Second,how to implement the singleton in a distributed environment(more than one jvm) so that there is only one instance of Singleton class.
Thanks.
Junilu Lacar
Bartender

Joined: Feb 26, 2001
Posts: 4782
    
    8

SearchFirst (← click): "double-checked locking is broken"


Junilu - [How to Ask Questions] [How to Answer Questions]
Max White
Ranch Hand

Joined: Jun 28, 2008
Posts: 85
I am sorry Junilu.
I know about the recent changes.My question was out of curiosity.
As you can see in the code , whats the need of having synchronized block after the line which checks for not null instance?
What if we put the not null check within the synchronized block?

Second,how to implement the singleton in a distributed environment(more than one jvm) so that there is only one instance of Singleton class.

Thanks for your time.
Junilu Lacar
Bartender

Joined: Feb 26, 2001
Posts: 4782
    
    8

I think this link: http://www.cs.umd.edu/~pugh/java/memoryModel/DoubleCheckedLocking.html will help explain the first question better than I can.

As for the "true" singleton question, the first thing that pops in my head (which may not necessarily be the best way) involves a web service implementation and a proxy/gateway that you distribute for use by all the JVMs that want to access the singleton.
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: singleton with lazy initialization