Reputation: 2251
I'm reading Java concurrency in practice which so far is really interesting
I've encountered Listing 3.1 with the following code example:
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;
}
}
I understand how theoretically this code snippet can go wrong.
I've decided to go and check it myself so I entered the code to my IDE and ran it for about 40 times and every single time the output was the same: 42.
So I'm curious, how many times (statistically) I should try and run it until I see a failed example and why is the failure so rare? I've tried searching on SO but all I found was: question about “Java Concurrency in Practice” example but it's irrelevant to my question since I do understand how it can happen but just curious on why is it so hard to get a failing execution
Thanks :)
Upvotes: 2
Views: 227
Reputation: 3690
Reordering can be done at the JIT level or at the CPU level. Your code is too short for the JIT to kick in so it would have to be the CPU.
For such a simple operation there is really no reason why the CPU would start messing up with your code so you will probably never observe that reordering and your program will always print 42.
The point of that example is not to say that it will break, but that in theory it could break.
See also: Why this broken program always runs?
Upvotes: 2