I was going through the use cases for volatile and I have encountered the below scenario:
private static boolean stop = false;
public static void main(String[] args) throws InterruptedException {
Thread runner = new Thread(new Runnable() {
@Override
public void run() {
int i = 0;
long start = System.currentTimeMillis();
while(!stop){
i++;
}
System.out.println("I m done after "+(System.currentTimeMillis() - start));
}
});
runner.start();
Thread.sleep(2000);
stop = true;
}
The above code runs indefinitely. Which is fine due to hoisting done by the compiler in an attempt to optimize the code. However, if I replace, i++ with some other statement e.g. System.out.println("Hello"). It stops after 2 seconds.
Why the behavior is like this? I am using jdk1.7.0_51.
Note: I know I should declare stop as volatile. However, I would like to know the reason for the behavior in the above case.