Reading \"Java Concurrency In Practice\", there\'s this part in section 3.5:
public Holder holder;
public void initialize() {
holder = new Holder(42);
}
The reason why this is possible is that Java has a weak memory model. It does not guarantee ordering of read and writes.
This particular problem can be reproduced with the following two code snippets representing two threads.
Thread 1:
someStaticVariable = new Holder(42);
Thread 2:
someStaticVariable.assertSanity(); // can throw
On the surface it seems impossible that this could ever occur. In order to understand why this can happen, you have to get past the Java syntax and get down to a much lower level. If you look at the code for thread 1, it can essentially be broken down into a series of memory writes and allocations:
Because Java has a weak memory model, it is perfectly possible for the code to actually execute in the following order from the perspective of thread 2:
Scary? Yes but it can happen.
What this means though is that thread 2 can now call into assertSanity before n has gotten the value 42. It is possible for the value n to be read twice during assertSanity, once before operation #3 completes and once after and hence see two different values and throw an exception.
EDIT
According to Jon Skeet, the AssertionError migh still occur with Java 8 unless the field is final.