GeeCON Prague 2014*
The moose likes OO, Patterns, UML and Refactoring and the fly likes Singleton ThreadSafe Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


JavaRanch » Java Forums » Engineering » OO, Patterns, UML and Refactoring
Bookmark "Singleton ThreadSafe" Watch "Singleton ThreadSafe" New topic
Author

Singleton ThreadSafe

Mohammed Yousuff
Ranch Hand

Joined: Oct 17, 2007
Posts: 198
How to make singleton Object without using syncronization code in getInstance() method.



My Thoughts : http://passion4java.blogspot.com
Try not to become a man of success but rather to become a man of value.
Rajkamal Pillai
Ranch Hand

Joined: Mar 02, 2005
Posts: 443
    
    1

Hi,

If the signature of getInstance() method for the singleton is of the form:-



the method is thread safe due to the synchronized keyword taking care of concurrency issues. Drop the 'synchronized' and your getInstance() is potentially liable for creation of multiple instances due to concurrent invocation by multiple threads.

Cheers,
Raj.
Brice Giesbrecht
Greenhorn

Joined: Mar 18, 2010
Posts: 4
To make your singleton, you can use a static initializer in your singleton.



To use it safely, you still have to make sure that the class remains threadsafe once you start adding functionality.
Mohammed Yousuff
Ranch Hand

Joined: Oct 17, 2007
Posts: 198
the above code loads the instance while startup, what if we need a lazy initialization, means we need to create the instance when client calls the getInstance() ... In that case we should not use synchronize the getInstance().... Any thoughts....???
Brice Giesbrecht
Greenhorn

Joined: Mar 18, 2010
Posts: 4
Using the static initializer does actually cause synchronization but it is implicit and done by the jvm during the class loading and initialization routine. So, you could say I sort of cheated by suggesting that.

To guarantee that only one process is executing in the critical section of your method that will be doing the actual initialization (like getInstance), somewhere down the line you will need to use synchronization explicitly (or implicitly like the static init). You can bury it using many layers but it will be there.

I am curious about the aversion to using synchronization. Can you provide a little info on that?
shivendra tripathi
Ranch Hand

Joined: Aug 26, 2008
Posts: 263
You can find more info in the link below.

http://shivendra-tripathi.blogspot.com/2010/01/singleton-pattern.html


SCJP 1.5(97%) My Blog
 
Don't get me started about those stupid light bulbs.
 
subject: Singleton ThreadSafe