Given the following class:
class Foo {
public volatile int number;
public int method1() {
int ret = number = 1;
return ret;
}
public int method2() {
int ret = number = 2;
return ret;
}
}
and given multiple threads calling method1() and method2() concurrently on the same Foo instance, can a call to method1() ever return anything other than 1?
The JLS 15.26 specifies:
Ted Hopp’s answer shows that Sun’s javac doesn’t follow this behaviour, possibly as an optimisation.
Due to the threading here, the behaviour of method1 would be undefined. If Sun’s compiler makes the behaviour constant then it doesn’t break from the undefined behaviour.