How to resolve Concurrent access issue in Singleton Design Pattern

It is advisable to initialize the object only when it’s required. Delay initialization required additional consideration to ensure that integrity of the singleton is maintained even in concurrent access.

Code snippet:
The integrity of singleton object in multi-threaded environment can be sustain by declaring getInstance() as synchronize method.

public  class Singleton
{
    //Declaring singleton field as static field
    //This field has static nature and will shared among all
    //instance of this class.
    private static Singleton singleton=null;
        
    //restrict object creation to this class only
    // Private access modifier play the critical role
    // to restrict the access of the constructor to the outsider.
    private Singleton()
    {
    }

    // Obtain instance of Singleton class with the help of
    // Singleton.getInstance() method.
    public static synchronized Singleton getInstance()
    {
      if(singleton==null)
      {
            singleton=new Singleton();
      }
        return singleton;
    }

    /// clone() method ....
    // additional stuff ...
}

Key points: 
  •  Singleton object is thread safe
  •  Only one thread will execute the getInstance() method that will reduce the concurrency.
  •  Every time getInstance() method is called additional housekeeping task executed to achieve mutual exclusion among the thread

Enter your email address to get our daily JOBS & INTERVIEW FAQ's Straight to your Inbox.

Make sure to activate your subscription by clicking on the activation link sent to your email


Enter your email address to get our daily JOBS & INTERVIEW FAQ's Straight to your Inbox.

Make sure to activate your subscription by clicking on the activation link sent to your email