Topic stuck in endless loop despite updated meaning

I was asked a question by a friend of mine and asked to explain why a program might end up in an infinite loop.

public class Test {
    private static boolean flag;
    private static int count;

    private static class ReaderThread extends Thread {
        public void run() {
            while (!flag)
                Thread.yield();
            System.out.println(count);
        }
    }

    public static void main(String[] args) {
        new ReaderThread().start();
        count = 1;
        flag = true;
    }
}

      

I was sure that this would not happen. But it did happen once (out of probably 50 times).

I cannot explain this behavior. Is there a catch I'm missing?

+3


source to share


1 answer


From the book - Java Concurrency In Practice (this example appears to be taken from the book itself).



When reads and writes occur on different threads, there is no guarantee that the read thread will see the value written by the other thread on time or even at all, because the threads can cache those values. To ensure that the write in memory is visible across streams, you must use synchronization or declare the variable as volatile .

+8


source







All Articles