请考虑以下代码片段。
public class Visibility {
private volatile SomeData data;
public static class SomeData {
private int number;
public SomeData(int number) {
this.number = number;
}
public int getNumber() {
return number;
}
}
public void initialize() {
data = new SomeData(42);
}
public SomeData getData() {
return data;
}
}
如果 number
字段是最终的,则任何看到 data
引用的线程都不是 null
(在其他线程调用 initialize
之后) code>) 也保证将 number
字段值视为 42
。
我们对非最终字段有同样的保证吗?
换句话说,某个线程是否有可能观察到非空值
data
引用,但 number
字段为 0
?
提前致谢!
最佳答案
某些线程不可能观察到非空数据引用,但数字字段为 0。
请参阅doc volatile :
This means that changes to a volatile variable are always visible to other threads. What's more, it also means that when a thread reads a volatile variable, it sees not just the latest change to the volatile, but also the side effects of the code that led up the change.
所以当你得到一个非空data
时,它一定已经成功启动,number
必须非零。
关于Java volatile 语义,JMM 保证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49799855/