views:

147

answers:

5

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 ?

+3  A: 

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.

Jon Skeet
+4  A: 

The reason why this is possible is that Java has a weak memory model. It does not guarantee ordering of read / writes. This particular problem can repro with the following 2 code snippets representing 2 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 thread2.

  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 Thread2 can now call into assertSanity before n has gotten the value 42. It is possible fro the value n to be read twice during assertSanity, once before operation #3 completes and once after and hence see 2 different values and throw an exception.

EDIT

According to Jon this is not possible (thankfully) with newer versions of Java due to updates to the memory model.

JaredPar
@Jared: I had forgotten that's only guaranteed for final fields. IIRC, the ECMA CLI specification is weak in this respect too, but the .NET memory model makes all writes effectively volatile. That's only IIRC though :)
Jon Skeet
@Jon you are correct on the .Net and ECMA angles. It makes for interesting fun though when reviewing changes to the F# libs and code base as they conform to the ECMA model.
JaredPar
Scary indeed. I learned from you answer something I had no idea regarding java memory model - This scares me because it can effectively mean 90% of every java code in the world is broke.Further more, the speed of your answer amazes me. From my calculation it took you a total of ~5min to answer my question! Thank you very much for the effort.
Maxim Veksler
The good guys at sun explain the described above "Happens Before" relationship.http://java.sun.com/javase/6/docs/api/java/util/concurrent/package-summary.html (#see Memory Consistency Properties section)
Maxim Veksler
A: 

looking at this from a sane perspective, if you assume that the statement

if(n != n)

is atomic (which I think is reasonable, but i dont know for sure), then the assertion exception could never be thrown.

twolfe18
does anyone care to explain the -1?
twolfe18
n != n is not atomic, it reads the values of n twice.
Maxim Veksler
A: 

The basic issue is that without proper synchronization, how writes to memory may manifest in different threads. The classic example:

a = 1;
b = 2;

If you do that on one thread, a second thread may see b set to 2 before a is set to 1. Furthermore, it's possible for there to be an unbounded amount of time between a second thread seeing one of those variables get updated and the other variable being updated.

R Samuel Klatchko
A: 

Well, in the book it states for the first code block that:

The problem here is not the Holder class itself, but that the Holder is not properly published. However, Holder can be made immune to improper publication by declaring the n field to be final, which would make Holder immutable; see Section 3.5.2

And for the second code block:

Because synchronization was not used to make the Holder visible to other threads, we say the Holder was not properly published. Two things can go wrong with improperly published objects. Other threads could see a stale value for the holder field, and thus see a null reference or other older value even though a value has been placed in holder. But far worse, other threads could see an up-todate value for the holder reference, but stale values for the state of the Holder.[16] To make things even less predictable, a thread may see a stale value the first time it reads a field and then a more up-to-date value the next time, which is why assertSanity can throw AssertionError.

I think JaredPar has pretty much made this explicit in his comment.

(Note: Not looking for votes here -- answers allow for more detailed info than comments.)