Enum singleton
The easiest way to implement Singleton, which is thread safe, is to use Enum
public enum SingletonEnum { INSTANCE; public void doSomething(){ System.out.println("This is a singleton"); } }
This code has been working since Enum appeared in Java 1.5
Double check lock
If you want to encode a βclassicβ singleton that works in a multi-threaded environment (since Java 1.5), you should use this one.
public class Singleton { private static volatile Singleton instance = null; private Singleton() { } public static Singleton getInstance() { if (instance == null) { synchronized (Singleton.class){ if (instance == null) { instance = new Singleton(); } } } return instance ; } }
This is not thread safe until 1.5, because the implementation of the volatile keyword is different.
Singleton early boot (works even before Java 1.5)
This implementation creates a singleton instance when the class loads and provides thread safety.
public class Singleton { private static final Singleton instance = new Singleton(); private Singleton() { } public static Singleton getInstance() { return instance; } public void doSomething(){ System.out.println("This is a singleton"); } }
Dan Moldovan Oct 02 '15 at 11:35 2015-10-02 11:35
source share