This week's book giveaway is in the Servlets forum.
We're giving away four copies of Murach's Java Servlets and JSP and have Joel Murach on-line!
See this thread for details.
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

Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Engineering » OO, Patterns, UML and Refactoring
Bookmark "Singleton ThreadSafe" Watch "Singleton ThreadSafe" New topic

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


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.

Brice Giesbrecht

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

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.

SCJP 1.5(97%) My Blog
I agree. Here's the link:
subject: Singleton ThreadSafe
Similar Threads
Single pattern
Hashtable's put method problem in locking
singleton class
Creating a utility managed bean, to move common code and use from different beans?
Tech Word Game