Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Thread stuck in infinite loop despite updated value

Tags:

java

I was given a question by my friend and was asked to explain why the program could get hung in 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 it cannot happen. But it did actually happen one time (out of probably 50 times).

I am not able to explain this behavior. Is there any catch that I am missing?

like image 202
Xiao Ziang Avatar asked May 17 '26 09:05

Xiao Ziang


1 Answers

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

When the reads and writes occur in different threads, there is no guarantee that the reading thread will see a value written by another thread on a timely basis, or even at all because threads might cache these values. In order to ensure visibility of memory writes across threads, you must use synchronization or declare variable as volatile.

like image 64
codingenious Avatar answered May 18 '26 21:05

codingenious



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!