"Java Concurrency in Practice" gives the following example of an unsafe class which due the nature of the java memory model may end up running forever or print 0.
The issue this class is trying to demonstrate is that the variables here are not "shared" between threads. So the value on thread sees can be different from another thread as they are not volatile or synchronized. Also due to the reordering of statements allowed by the JVM ready=true maybe set before number=42.
For me this class always works fine using JVM 1.6. Any idea on how to get this class to perform the incorrect behavior (i.e. print 0 or run forever)?
public class NoVisibility {
private static boolean ready;
private static int number;
private static class ReaderThread extends Thread {
public void run() {
while (!ready)
Thread.yield();
System.out.println(number);
}
}
public static void main(String[] args) {
new ReaderThread().start();
number = 42;
ready = true;
}
}
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.
prints the following showing its fliping the value, but gets stuck.
If I add
-XX:+PrintCompilation
this switch happens about the time you seeWhich 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 tofalse
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 seesfalse
for the same field.