假设我们正在使用双重检查锁定实例化一个单例:
public static Instance getInstance() {
if (this.instance == null) {
synchronized(Instance.class) {
if (this.instance == null) {
this.instance = new Instance();
}
}
}
return this.instance;
}
问题在于程序的语义,如果instance变量是可变的并且双重检查锁定将被删除。
private volatile static Instance instance;
public static Instance getInstance() {
if (this.instance == null) {
this.instance = new Instance();
}
return this.instance;
}
类只会实例化一次吗?或者,换句话说,易失性读取是否会以这样一种方式发生冲突,即两个线程将看到null引用的值并执行双重实例化?
我知道易失性写入和易失性读取之间的发生在之前的关系,并且易失性禁止缓存(因此所有读取和写入都将在主内存中执行,而不是在处理器的缓存中),但在这种情况下尚不清楚并发易失性读取。
PS:问题不在于单例模式的应用(这只是一个问题很明显的例子),只是关于双重检查锁定是否可以替换为易失性读取 - 易失性写入而不改变程序语义,仅此而已比起那个来说。
天涯尽头无女友
白猪掌柜的
慕工程0101907
相关分类