双重检查锁 & volatile保证可见性(变量值改动后及时从工作内存写回主内存)和有序性(指令不可重排)
public class Singleton { private static volatile Singleton singleton = null; private Singleton(){} public static Singleton getSingleton(){ if(singleton == null){ synchronized (Singleton.class){ if(singleton == null){ singleton = new Singleton(); } } } return singleton; } }
利用JVM类加载的原理保证只初始化一下实例,利用内部类,保证使用时才初始化加载(满足了赖加载)
public class Singleton { private static class Holder { private static Singleton singleton = new Singleton(); } private Singleton(){} public static Singleton getSingleton(){ return Holder.singleton; } }
不管采取何种方案,请时刻牢记单例的三大要点:
https://www.cnblogs.com/andy-zhou/p/5363585.html
原文:https://www.cnblogs.com/genggeng/p/10013781.html