This week's book giveaway is in the OO, Patterns, UML and Refactoring forum. We're giving away four copies of Refactoring for Software Design Smells: Managing Technical Debt and have Girish Suryanarayana, Ganesh Samarthyam & Tushar Sharma on-line! See this thread for details.
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.
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.
Joined: Oct 17, 2007
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....???
Joined: Mar 18, 2010
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?