Reading a book, and this code comes up:
public class Test {
private static boolean ready = false;
private static int number = 0;
public static class ListenerThread extends Thread {
public void run() {
while(!ready) {
Thread.yield();
}
System.out.println(number);
}
}
public static void main (String[] args) {
new ListenerThread().start();
number = 10;
ready = true;
}
}
The main points I was surprised about were mentioned by the author relatively quickly.
They said ListenerThread might never terminate. I thought about this for a few days (in the back of my head), and my only conclusion is that it might be cached by that ListenerThread. Is that true? Would making
ready
volatile solve the problem (since it shouldn't cache it anymore)?They also said the program might print 0. I understand now that Java might reorder the instructions, so ready becomes true to another thread before number is changed. Is there any method (technique), besides putting those instructions in a synchronized blocks solve the problem (on a central lock value)? I was thinking maybe implement notify()/wait(), but I feel it would suffer the same consequences. What is the best way to avoid the problem?
Thank you!
EDIT:
I just feel that I've read through a lot of code, and few bothered to protect against reordering in multiple threads. How common is this?