How do visibility problems occur in Java concurrency? [duplicate]

陌路散爱 提交于 2020-01-15 09:47:30

问题


I am reading the book: "Java Concurrency in Practice" to better understand how java concurrency works. On chapter 3 section 3.1:Visibility There is and example in which the book tries to show how visibility problems occur. Here is the example code (Listing 3.1 in the book):


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;
    }
}

The book says that the NoVisibility could loop forever because the value of ready might never become visible to the reader thread. How is that possible. My general understanding is that ready will become true at a certain time anyhow. But I can't understand why this might not happen and the loop goes forever. Can someone help me to understand this better.


回答1:


Because ready isn't marked as volatile and the value may be cached at the start of the while loop because it isn't changed within the while loop. It's one of the ways the jitter optimizes the code.

So it's possible that the thread starts before ready = true and reads ready = false caches that thread-locally and never reads it again.

Check out the volatile keyword.

Source



来源:https://stackoverflow.com/questions/15322527/how-do-visibility-problems-occur-in-java-concurrency

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!