I was reading the book Effective Java by Joshua Bloch and was shocked to read this. The author shows this code snippet in chapter on Concurrency:
public class StopThread {
private static boolean stopRequested;
public static void main(String[] args) throws InterruptedException {
Thread backgroundThread = new Thread(() -> {
int i = 0;
while (!stopRequested) {
i++;
}
});
backgroundThread.start();
TimeUnit.SECONDS.sleep(1);
stopRequested = true;
}
}
then he goes on to say:
In the absence of synchronization, it is quote acceptable for the virtual machine to transform the code:
while (!stopRequested)
i++;
into this code:
if (!stopRequested)
while (true)
i++;
I am shocked at this. It changes the meaning of the code completely. The two are not equivalent so how can the VM make such an optimization (in fact its incorrect to even term this as optimization)? Can anyone explain it to me?
2