The problem you have is that you are not waiting long enough for the code to be optimised and the value to be cached.
When a thread on an x86_64 system reads a value for the first time, it gets a thread safe copy. Its only later changes it can fail to see. This may not be the case on other CPUs.
If you try this you can see that each thread is stuck with its local value.
public class RequiresVolatileMain {
static volatile boolean value;
public static void main(String... args) {
new Thread(new MyRunnable(true), "Sets true").start();
new Thread(new MyRunnable(false), "Sets false").start();
}
private static class MyRunnable implements Runnable {
private final boolean target;
private MyRunnable(boolean target) {
this.target = target;
}
@Override
public void run() {
int count = 0;
boolean logged = false;
while (true) {
if (value != target) {
value = target;
count = 0;
if (!logged)
System.out.println(Thread.currentThread().getName() + ": reset value=" + value);
} else if (++count % 1000000000 == 0) {
System.out.println(Thread.currentThread().getName() + ": value=" + value + " target=" + target);
logged = true;
}
}
}
}
}
prints the following showing its fliping the value, but gets stuck.
Sets true: reset value=true
Sets false: reset value=false
...
Sets true: reset value=true
Sets false: reset value=false
Sets true: value=false target=true
Sets false: value=true target=false
....
Sets true: value=false target=true
Sets false: value=true target=false
If I add -XX:+PrintCompilation
this switch happens about the time you see
1705 1 % RequiresVolatileMain$MyRunnable::run @ -2 (129 bytes) made not entrant
1705 2 % RequiresVolatileMain$MyRunnable::run @ 4 (129 bytes)
Which suggests the code has been compiled to native is a way which is not thread safe.
if you make the value volatile
you see it flipping the value endlessly (or until I got bored)
EDIT: What this test does is; when it detect the value is not that threads target value, it set the value. ie. thread 0 sets to true
and thread 1 sets to false
When the two threads are sharing the field properly they see each others changes and the value constantly flips between true and false.
Without volatile this fails and each thread only sees its own value, so they both both changing the value and thread 0 see true
and thread 1 sees false
for the same field.
ReaderThread
becomes active before the assignments are made, and then the scheduler ignores theyield()
calls). On a multi-core machine there is no way forReaderThread
to permanently block execution of the main thread, and thus the runs-forever error will never occur. – Lendlease