Oracle documentation states that:
Reads and writes are atomic for reference variables and for most primitive variables (all types except long and double).
Now I wonder why the volatile keyword is necessary in the following example to prevent an endless loop - the change of the int variable should be atomic and therefore instantly visible to everyone, shouldn't it?
public class HelloWorld
{
// This doesn't work as expected
private static int x = 0;
//Following would work: private volatile static int x = 0;
public static void main(String []args) throws Exception
{
Thread t1 = new Thread(() -> {
try
{
Thread.sleep(1000);
x = 1; //Should be atomic, right?
} catch (InterruptedException e) {}
});
System.out.println("Begin");
t1.start();
//The evaluation of the condition should also be atomic, right?
while(x == 0)
{
}
t1.join();
System.out.println("End");
}
}