If I have this:
public class Foo {
public int bar;
public Foo(int bar) {
this.bar = bar;
synchronized (Foo.class) {
Foo.instance = this;
Foo.class.notify();
}
}
public static Foo instance;
public static Foo instance() {
synchronized (Foo.class) {
if (Foo.instance == null) {
Foo.class.wait();
}
return instance;
}
}
}
And in another class I have this, at any and all unspecified points in the future, assuming I have NOT yet altered the value of Bar by any means:
int baz = Foo.instance().bar;
Is there any possibility at all of having Foo . Instance ( ) . Bar
return uninitialized gibberish? My thought is that, since I have assured that nothing will ever try to access Bar
before the Instance variable is set, that the JIT compiler cannot optimize away anything and must read from main memory, but is this true? Is it possible for it to somehow get compiled so that it instead pulls 0
(which was the value of Bar
before it was set to the new value in the constructor).