what happens after writing to a volatile variable?

余生颓废 提交于 2019-12-08 16:14:27

问题


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 ?


回答1:


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 of y if they try to read it. Threads that don't read x 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.



来源:https://stackoverflow.com/questions/7129015/what-happens-after-writing-to-a-volatile-variable

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!