Consider the Java example below. Notice that neither of the class member variables are declared to be volatile
. If I am understanding the memory model and "happens before" rules correctly, a Java implementation could optimize the run()
method so that it runs forever, even if another thread calls the stopNow()
method. This can happen because there is nothing in the run()
method that forces the thread to read the value of stop
more than once. Is that correct? If not, why not?
class Example implements Runnable {
boolean stop = false;
int value = 0;
public void stopNow() {
stop = true;
}
public int getValue() {
return value;
}
@Override
public void run() {
// Loop until stop is set to true.
while (!stop) {
++value;
}
return;
}
}