【发布时间】:2017-05-08 13:26:04
【问题描述】:
我的问题与this post有关。
public class SafeDCLFactory {
private volatile Singleton instance;
public Singleton get() {
if (instance == null) { // check 1
synchronized(this) {
if (instance == null) { // check 2
instance = new Singleton(); // store
}
}
}
return instance;
}
}
这是一场数据竞赛。线程 1 可以读取 instance(检查 1),而线程 2 写入(存储)。
为什么安全? store 操作在这里是原子的吗?如果没有怎么办?
【问题讨论】:
-
对引用字段的写入始终是原子的。
volatile是确保引用对象安全发布的一种方式。
标签: java multithreading java-memory-model