Consider the snippet taken from the book Java Concurrency in Practice by Joshua Bloch-
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; // Statement 1
ready = true; // Statement 2
}
}
For the main thread started by JVM, is it guaranteed that statement 1 is going to be executed before statement 2.
I perfectly understand that the ReaderThread might not be able to see the updated value of above two static variables. I am not asking for the solution. But if the statement 1 was executed before statement 2, is it still possible for the ReaderThread to see the updated value for ready & not for number? Is this what reordering means in general?
A paragraph at the bottom of the page in the same book reveals an insight into this-
There is no guarantee that operations in one thread will be performed in the order given by the program, as long as the reordering is not detectable from within that thread—even if the reordering is apparent to other threads.
A little confusion here-
The author is saying ... as long as the reordering is not detectable from within that thread... while at the same time, he says-
—even if the reordering is apparent(clearly visible) to other threads.
If in case, the reordering is clearly visible to other threads, why is he saying at the same time "as long as the reordering is not detectable from within that thread"? If the reordering is visible, that means it is detectable also. Isn't it?