Not thread-safe Object publishing

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:

  1. Alloc memory to pointer1
  2. Write 42 to pointer1 at offset 0
  3. Write pointer1 to someStaticVariable

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:

  1. Alloc Memory to pointer1
  2. Write pointer1 to someStaticVariable
  3. Write 42 to pointer1 at offset 0

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.


The Java memory model used to be such that the assignment to the Holder reference might become visible before the assignment to the variable within the object.

However, the more recent memory model which took effect as of Java 5 makes this impossible, at least for final fields: all assignments within a constructor "happen before" any assignment of the reference to the new object to a variable. See the Java Language Specification section 17.4 for more details, but here's the most relevant snippet:

An object is considered to be completely initialized when its constructor finishes. A thread that can only see a reference to an object after that object has been completely initialized is guaranteed to see the correctly initialized values for that object's final fields

So your example could still fail as n is non-final, but it should be okay if you make n final.

Of course the:

if (n != n)

could certainly fail for non-final variables, assuming the JIT compiler doesn't optimise it away - if the operations are:

  • Fetch LHS: n
  • Fetch RHS: n
  • Compare LHS and RHS

then the value could change between the two fetches.