As expected the reader thread in below program runs forever since it cached the stop flag(non-volatile) on its local processor's cache. Whereas, as soon as I uncomment the println on reader thread, the flag gets updated flag value and program stops. How this is possible as writer thread only writes flag to its own local cache and not yet flushed to main memory?
Note: running this program in MacBook Pro x86 architecture machine.
public class FieldVisibility {
boolean stop = false;
public static void main(String[] args) throws Exception {
FieldVisibility fv = new FieldVisibility();
Runnable writerThreadJob = () -> { fv.writer(); };
Runnable readerThreadJob = () -> { fv.reader(); };
Thread writerThread = new Thread(writerThreadJob);
Thread readerThread = new Thread(readerThreadJob);
readerThread.start();
try { Thread.sleep(2); } catch (InterruptedException e) {}
writerThread.start();
}
private void writer() {
stop = true;
}
private void reader() {
while (!stop) {
// System.out.println("stop is still false...");
}
}
}