饿汉式,instance在类加载化时完成初始化,线程安全
package cookie; public class SingletonAtOnce { private SingletonAtOnce() { } private static final SingletonAtOnce instance = new SingletonAtOnce(); public static SingletonAtOnce getInstance() { return instance; } }
懒汉式,双锁检查机制保证线程安全
package cookie; public class SingletonDCL { private SingletonDCL() { } private static volatile SingletonDCL instance; public static SingletonDCL getInstance() { if (instance == null) { synchronized (SingletonDCL.class) { if (instance == null) { instance = new SingletonDCL(); } } } return instance; } }
私有内部类持有,也属于懒汉式,读ClassHolder中的instance时,导致ClassHolder加载,加载时完成instance的初始化,线程安全
package cookie; public class SingletonClassHolder { private SingletonClassHolder() { } private static class Holder { public static SingletonClassHolder instance = new SingletonClassHolder(); } public static SingletonClassHolder getInstance() { return Holder.instance; } }