Instant Loading
public class Singleton {private static final Singleton uniqueInstance = new Singleton();private Singleton() {}public static Singleton getInstance() {return uniqueInstance;}}Delayed loading-dual detection shackles
Note the volatile keyword
public class Singleton {private volatile static Singleton uniqueInstance;private Singleton() {}public static Singleton getInstance() {if (uniqueInstance == null) {synchronized (Singleton.class) {if (uniqueInstance == null) {uniqueInstance = new Singleton();}}}return uniqueInstance;}}Delayed loading-internal static class
It is thread-safe to load internal static classes when they are referenced for the first time.
public class Singleton {private Singleton() {}public static Singleton getInstance() {return Nested.uniqueInstance;}static class Nested {private static final Singleton uniqueInstance = new Singleton();}}Singleton mode serialization
Note that the implementation of the readresolve method, and the instance domains referenced by the object must be declared as transient. For details, see article 77th of objective Java.
import java.io.Serializable;public class Singleton implements Serializable {private static final Singleton uniqueInstance = new Singleton();private transient String element = "singleton";private Singleton() {}public static Singleton getInstance() {return uniqueInstance;}private Object readResolve() {return uniqueInstance;}}Enumeration class
The single-instance best implementation method provides a serialization mechanism to prevent multiple instantiation and thread safety.
public enum Singleton {INSTANCE;// elements & methods}
Singleton mode Summary