I have theoretical question about memory visibility. Here is sample code:
public class TwoThreadApp {
private static class A {
int x = 1;
}
public static void main(String[] arg) throws InterruptedException {
A a = new A();
Thread t2 = new Thread(() -> {
while (true) {
if (a.x == 2) {
System.out.println(a.x);
return;
}
// IO operation which makes a.x visible to thread "t2"
System.out.println("in loop");
}
});
t2.start();
Thread.sleep(100);
a.x = 2;
}
}
- Without
System.out.println("in loop")
programs works indefinitely, which is expected behavior. - But with
System.out.println("in loop")
it is always completes, which is not expected, because a.x is not volatile and there is no synchronized blocks.
My env: ubuntu 16.04, openjdk 1.8.0_131
Why it behaves this way?