what happens after writing to a volatile variable?
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 ?
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.
精彩评论