javastaticsingletonlazy-initializationstatic-block

Singleton object- In static block or in getInstance(); which should be used


Below are two ways to implement a singleton. What are the advantages and disadvantages of each?

Static initialization:

class Singleton {
    private Singleton instance;
    static {
        instance = new Singleton();
    }
    public Singleton getInstance() {
        return instance;
    }
}

Lazy initialization is:

class Singleton {
    private Singleton instance;
    public Singleton getInstance(){
        if (instance == null) instance = new Singleton();
        return instance;
    }
}

Solution

    1. Synchronized Accessor

      public class Singleton {
          private static Singleton instance;
      
          public static synchronized Singleton getInstance() {
              if (instance == null) {
                  instance = new Singleton();
              }
              return instance;
          }
      }
      
      • lazy load
      • low perfomance
    2. Double Checked Locking & volatile

      public class Singleton {
          private static volatile Singleton instance;
          public static Singleton getInstance() {
              Singleton localInstance = instance;
              if (localInstance == null) {
                  synchronized (Singleton.class) {
                      localInstance = instance;
                      if (localInstance == null) {
                          instance = localInstance = new Singleton();
                      }
                  }
              }
              return localInstance;
          }
      }
      
      • lazy load
      • high perfomance
      • JDK should be 1,5 ++
    3. On Demand Holder idiom

      public class Singleton {
      
          public static class SingletonHolder {
              public static final Singleton HOLDER_INSTANCE = new Singleton();
          }
      
          public static Singleton getInstance() {
              return SingletonHolder.HOLDER_INSTANCE;
          }
      }
      
      • lazy load
      • high performance
      • cant be used for non static class fields