为什么在双重检查锁定中使用 volatile [英] Why is volatile used in double checked locking
问题描述
从Head First设计模式书中,双检查锁定的单例模式已经实现如下:
From Head First design patterns book, the singleton pattern with double checked locking has been implemented as below:
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
的使用是否会破坏使用双重检查锁定的目的,即性能?
I don't understand why volatile
is being used. Doesn't volatile
usage defeat the purpose of using double checked locking i.e performance?
推荐答案
理解为什么需要 volatile
的一个很好的资源来自 JCIP 书.维基百科对该材料也有体面的解释.
A good resource for understanding why volatile
is needed comes from the JCIP book. Wikipedia has a decent explanation of that material as well.
真正的问题是线程A
可能会在instance
构建完成之前为instance
分配内存空间.Thread B
将看到该分配并尝试使用它.这会导致 Thread B
失败,因为它使用的是 instance
的部分构造版本.
The real problem is that Thread A
may assign a memory space for instance
before it is finished constructing instance
. Thread B
will see that assignment and try to use it. This results in Thread B
failing because it is using a partially constructed version of instance
.
这篇关于为什么在双重检查锁定中使用 volatile的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!