Reading "Java Concurrency In Practice", there's this part in section 3.5:
public Holder holder;
public void initialize() {
holder = new Holder(42);
}
Besides the obvious thread safety hazard of creating two instances of Holder
, the book claims a possible publishing issue can occur.
Furthermore, 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 way I can think of that can allow such ridiculous behavior is if the Holder
constructor would not be blocking, so a reference would be created to the instance while the constructor code still runs in a different thread.
Is this possible?