I read Dejan Bosanac wrote “Singletons and lazy loading” at OnJava. He introduced Initialization on Demand Holder idiom (IODH). Then I learned how to refactor lazy loaded singletons.

public class Singleton {

  static class SingletonHolder {
    static Singleton instance = new Singleton();
  }

  public static Singleton getInstance() {
    return SingletonHolder.instance;
  }

}

That’s really useful and neat.

Singleton convention way:

public final class Singleton {
	private static Singleton singleton = null;
	
	private Singleton() {}

	public static synchronized Singleton getInstance() {			
	    if (singleton == null) {
		singleton = new Singleton();
	    }		
	    return singleton;
	}
}

Ref:

Initialization on Demand Holder idiom

Double-checked locking

Advertisements