I'm studying Java Concurrency in Practice and there it is explained why the following snippet of code is bad:
public class NoVisibility {
private static boolean ready;
private static int number;
private static class ReaderThread extends Thread {
public void run() {
while (!ready) {
Thread.yield();
System.out.println(number);
}
}
public static void main(String[] args) {
new ReaderThread().start();
number = 42;
ready = true;
}
}
This code may print 0 or loop forever.
While it is easy to understand why NoVisibility
could print 0 instead of 42 (due to re-ordering issue),
I'm a little confused about the infinite loop.
What is a practical scenario where an infinite loop may occurr, in this code?
The loop stops when ready
is set to true
. And ready
is set to true
by the main thread. But since the ready
field is not volatile, the looping thread might continue to see a cached value: false
.
The volatile
keyword guarantees that all the threads reading a volatile field will actually see the last value stored in this field by any other thread. Without volatile
, you don't have this guarantee.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With