No, it is bad:
public static Singleton getInstance() { // new "singleton" for every method call Singleton s = new Singleton(); ^^^^^^^^^^^^^^ if (instance.compareAndSet(null, s)) { synchronized (s) { s.init(); } } return instance.get(); }
Using AtomicReference is a good idea, but it will not work because Java does not have a lazy rating.
Classic single-threaded post 1.5 methods:
Eager Singleton:
public final class Singleton{ private Singleton(){} private static final Singleton INSTANCE = new Singleton(); public Singleton getInstance(){return INSTANCE;} }
Lazy Singleton with an internal holder class:
public final class Singleton{ private Singleton(){} private static class Holder{ private static final Singleton INSTANCE = new Singleton(); } public Singleton getInstance(){return Holder.INSTANCE;} }
Enum Singleton:
public enum Singleton{ INSTANCE; }
You should probably stick to one of these
source share