erdogany
6/19/2013 - 8:59 AM

Lazy singleton in Java that uses double-checked locking

Lazy singleton in Java that uses double-checked locking

public class SingletonDemo {
  private static volatile SingletonDemo instance = null;
 
  private SingletonDemo() {       }
 
  public static SingletonDemo getInstance() {
    if (instance == null) { // check 1 (no need to lock if already initialized)
      synchronized (SingletonDemo .class){
        if (instance == null) { // check 2 (this makes it double-checked locking)
          instance = new SingletonDemo ();
        }
      }
    }
    return instance;
  }
}