// run in server JVM to show effect of hoisting non-volatile _flag into t2. public class VolatileDemo { volatile boolean _flag = false; void run() { Thread t1 = new Thread(new Runnable() { public void run() { try { Thread.sleep(1000); _flag = true; } catch(InterruptedException ie) { /* ignore */ } } }); Thread t2 = new Thread(new Runnable() { public void run() { System.out.println("_flag = "+_flag); while(!_flag) { // this may become an infinite loop } System.out.println("_flag = "+_flag); } }); t1.start(); t2.start(); try { t1.join(); t2.join(); } catch(InterruptedException ie) { /* ignore */ } } public static void main(String[] args) { (new VolatileDemo()).run(); } }