How do you write a Thread-Safe Singleton

How do you write a Thread-Safe Singleton?

The following are the steps to write a thread-safe singleton:

- Declare a Boolean variable, ‘instantiated’, to know the status of instantiation of a class, an object of Object class and a variable of the same class with initial value as null.

- Write a private constructor of this class.

- Override getInstance() method. Check the Boolean state of the instance variable ‘instantiated’. If it is false, write a ‘synchronized’ block and test for the current class instance variable. If it is null create an object of the current class and assign it to the instance variable.

The following code illustrates this :
public class SampleSingleton
{
   private static boolean initialized = false;
   private static Object obj = new Object();
   private static SampleSingleton instance = null;
   private SampleSingleton()
   {
       // construct the singleton instance
   }
   public static SampleSingleton getInstance()
   {
       if (!initialized)
       {
            synchronized(obj)
           {
               if (instance == null)
               {
                   instance = new SampleSingleton();
                   initialized = true;
               }
           }
       }
   return instance;
   }
}
What is the Reactor pattern?
What is the Reactor pattern? - The Reactor pattern is an architectural pattern that allows demultiplexing of event-driven applications...
What are Process Patterns?
What are Process Patterns? - Methods, best practices, techniques for developing an Object-Oriented software comprises a process pattern...
What are Collaboration Patterns?
What are Collaboration Patterns? - Repeatable techniques which are utilized by people of different teams for helping them work together...
Post your comment