问题
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