写入易失性变量后会发生什么?
我想知道写入易失性变量是否会强制jvm将所有非易失性变量同步到内存,例如,以下代码中会发生什么:
volatile int x;
int y;
y=5;
x=10;
x将被写入内存,但是y会发生什么?它也会被写入内存吗?
I wonder if writing to a volatile variable will force jvm to synchronize all non-volatile variables to the memory, so for example, what will happen in the following code:
volatile int x;
int y;
y=5;
x=10;
x will be written to the memory, but what will happen to y ? will it be also written to memory ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
是的,根据 Java 语言规范 (第三版)——特别是第 17.4.4 节——每个看到 x 的新值的线程随后也会看到 y 的新值,如果他们尝试阅读它。不读取
x
的线程不保证会受到影响。但请注意,JLS 第二版的内存模型中不存在这种保证。在那里,易失性读取和写入对非易失性存储器访问的顺序没有影响。
Yes, under the rules of the Java Language Specification (third edition) -- in particular section 17.4.4 -- every thread that sees the new value of
x
will subsequently also see the new value ofy
if they try to read it. Threads that don't readx
are not guaranteed to be affected.Beware, however, that this guarantee was not present in the memory model of the second edition of JLS. There, volatile reads and writes had no effect on the ordering of non-volatile memory accesses.