Reading Java concurrency in practice, section 3.5: Claim is raised that
public Holder holder;
public void initialize() {
holder = new Holder(42);
}
Besides the obvious thread safely hazard of creating 2 instances of Holder the book claims a possible publishing issue can occur, further more for a Holder class such as
public Holder {
int n;
public Holder(int n) { this.n = n };
public void assertSanity() {
if(n != n)
throw new AssertionError("This statement is false.");
}
}
an AssertionError can be thrown !
How is this possible ? The only this I can think of that can allow such ridiculous behavior is if the Holder constructor would not be blocking, so a reference would be creates to the instance while the constructor code still runs in a different thread. Is this possible ?