1. Double check lock
public class Singleton {
private static volatile Singleton instance;
private Singleton(){}
public static Singleton getInstance(){
if (instance == null) {
synchronized (Singleton.class) {
if (instance == null) {
instance = new Singleton();
}
}
}
return instance;
}
}
Copy the code
2. Inner class implementation
public class Singleton { private static class SingletonHolder{ public static Singleton instance = new Singleton(); } private Singleton(){} public static Singleton getInstance(){ return SingletonHolder.instance; }}Copy the code
3. The enumeration
public enum Singleton {
INSTANCE;
}
Copy the code