double checked locking单例模式
作者:互联网
/**
* double checked locking
*/
public class Singleton {
private Singleton() {
}
private static volatile Singleton instance = null;
public static Singleton getInstance() {
if (instance == null) {
synchronized (Singleton.class) {
if (instance == null) {
instance = new Singleton();
}
}
}
return instance;
}
}
为甚么这样做?
避免synchronized 内过多代码块,从而影响效率。
为甚么要加volatile?
避免指令重排从而影响到代码准确性。
标签:Singleton,checked,synchronized,double,locking,private,instance,static,null 来源: https://www.cnblogs.com/coding8832/p/14475259.html