问题
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