DEV Community

Discussion on: Effective Java Tuesday! Singletons!

Collapse
 
kylec32 profile image
Kyle Carter

Interesting. I see no reason that you couldn't do that if it made sense to put the singleton in such a nested class. Something to keep in mind if the option ever comes up.

Collapse
 
raipc profile image
Anton Rybochkin

I thought that was the official way to create lazy singletons without synchronization.

public class CEO {
  private CEO() { }

  public static CEO getInstance() {
    return InstanceHolder.instance;
  }

  public void fire(Employee slacker) { ... }

  private static final class InstanceHolder {
    private static final CEO instance = new CEO();
  }
}
Thread Thread
 
kylec32 profile image
Kyle Carter

Will you look at that! Still never seen that but you are 100% correct this would allow lazy initialization without synchronization. Thanks for educating me about that.