As per the book “Java concurrency in practice”, the below code might execute forever or value of number may still be 0 when ready is true and the recommendation was to define the variables as volatile. However the below listed program always seems to return the correct value (42) instead of stale value even after I tried this multiple times. Is this a phenomenon that occurs very rarely?
public class NoVisibility {
private static boolean ready;
private static int number;
private static class ReaderThread extends Thread{
public void run(){
System.out.println("Thread started =" + ready + " " + number);
while(!ready){
Thread.yield();
}
System.out.println("value is" + number);
}
}
public static void main(String[] args) throws InterruptedException {
new ReaderThread().start();
Thread.sleep(10000);
number = 42;
ready = true;
}
}
