From 头先设计模式手册中,具有双重检查锁定的单例模式已实现如下:
public class Singleton {
private volatile static Singleton instance;
private Singleton() {}
public static Singleton getInstance() {
if (instance == null) {
synchronized (Singleton.class) {
if (instance == null) {
instance = new Singleton();
}
}
}
return instance;
}
}
我不明白为什么volatile
正在使用中。没有volatile
用法违背了使用双重检查锁定的目的,即性能?
理解原因的好资源volatile
所需要的来自于JCIP书。维基百科有一个体面的解释也是该材料的。
真正的问题是Thread A
可以分配一个内存空间instance
在施工完成之前instance
. Thread B
将看到该作业并尝试使用它。这导致Thread B
失败,因为它使用的是部分构建的版本instance
.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)