This week's giveaway is in the EJB and other Java EE Technologies forum.
We're giving away four copies of EJB 3 in Action and have Debu Panda, Reza Rahman, Ryan Cuprak, and Michael Remijan 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 EJB 3 in Action this week in the EJB and other Java EE Technologies 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: 4419
    
    5

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: 4419
    
    5

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.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: singleton with lazy initialization
 
Similar Threads
Singleton
'double checked locking' in singleton - not thread safe
Singleton Class ?
Question regarding Singleton pattern
Test question - need help