Based on
What does volatile do? http://www.cs.umd.edu/~pugh/java/memoryModel/jsr-133-faq.html#incorrectlySync
and
New guarantees for volatile http://www.ibm.com/developerworks/library/j-jtp03304/
class VolatileExample {
int x = 0;
volatile boolean v = false;
public void writer() {
x = 42;
v = true;
}
public void reader() {
if (v == true) {
//uses x - guaranteed to see 42.
}
}
}
It seems that.
1a) write to non-volatile variable x
1b) write to volatile variable v
1a can never moved pass 1b
I was wondering, if I modify the source code to the following
class VolatileExample {
int x = 42;
volatile boolean v = true;
public void writer() {
v = false;
x = 0;
}
public void reader() {
if (v == true) {
//uses x - guaranteed to see 42?????
}
}
}
Can the following sequence be permuted?
2a) write to volatile variable v
2b) write to non-volatile variable x
I was wondering, can 2b ever move before 2a? This is because if 2b able to move before 2a, reader can no longer guaranteed to see 42 within if block.
I feel 2b can be move before 2a based on the following information.
http://www.cs.umd.edu/~pugh/java/memoryModel/jsr-133-faq.html#reordering
Writing to a volatile field has the
same memory effect as a monitor
release, and reading from a volatile
field has the same memory effect as a
monitor acquire.
This means that any memory operations
which were visible to a thread before
exiting a synchronized block are
visible to any thread after it enters
a synchronized block protected by the
same monitor, since all the memory
operations happen before the release,
and the release happens before the
acquire.
and Roach Motels and The Java Memory Model
volatile_v = true; <-- monitor release
non_volatile_x = 42;
(volatile_v will act as a roach motels, and it is fine for non_volatile_x to move into roach motels)
non_volatile_x = 42;
volatile_v = true; <-- monitor release
(volatile_v will act as a roach motels, and it is not OK for non_volatile_x to move out from roach motels)
Well we know that a write to a volatile variable can’t be reordered with respect to any previous read or write (as of Java5), but this isn’t true the other way around. So reordering the program to x = 0; v = false; would be correct as I understand it.
After we write to v we’re guaranteed that when reading v that every action that happened before writing to v will be visible, but it doesn’t say anything about actions AFTER writing to v – those may or may not have happened and can even be reordered to happen before v is written to.