I tried to use examples from JCIP, and the program below did not work, but even if I execute it, I will say that it always works 20 times, which means that ready and number become visible, even if in this case it should be
public class NoVisibility { private static boolean ready; private static int number; private static class ReaderThread implements Runnable { public void run() { while (!ready) Thread.yield(); System.out.println(number); } } public static void main(String[] args) { System.out.println(Runtime.getRuntime().availableProcessors());
On my machine, it always prints
4 -- Number of Processors 42 42 42 42 42
According to Listing 3.1 of JCIP It should sometimes print 0 or should never terminate it also suggest that there is no gaurantee that ready and number written by main thread will be visible to reader thread
Update I added 1000 ms to sleep in the main thread after all the threads stayed on the same output. I know the program is broken. And I expect her to act like that.
source share