Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java, visibility and infinite loop occurrence

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?

like image 934
Nico Giangregorio Avatar asked Jan 17 '23 20:01

Nico Giangregorio


1 Answers

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.

like image 157
JB Nizet Avatar answered Jan 28 '23 06:01

JB Nizet