Search code examples
javac++staticsingletonlazy-initialization

Initialization On Demand Holder idiom


This is the implementation mostly seen on the web

private static class LazySomethingHolder {
  public static Something something = new Something();
}

public static Something getInstance() {
  return LazySomethingHolder.something;
}

Is the following simpler variation correct, if not what is wrong with it? Is the problem specific to java or also present in C++?

public static Something getInstance() {
  private static Something something = new Something();
  return something;
}

Solution

  • You cannot have static local variables in Java.

    Simpler alternatives are

    private static final Something something = new Something();
    
    public static Something getInstance() {
      return something;
    }
    

    or my preference if for.

    enum Something {
        INSTANCE;
    }
    

    The only problem with these patterns is that if you have multiple instances you want lazily loaded, you need to have a class each, or loading one will mean loading them all.