Am I correct in my understanding that due to out-of-order execution I can get a NullPointerException? In other words: there's no guarantee that because I read a non-null "b" I'll read a non-null "a"?
Assuming that the values assigned to a
and b
or non-null, I think your understanding is not correct. The JLS says this:
(1) If x and y are actions of the same thread and x comes before y in program order, then hb(x, y).
(2) If an action x synchronizes-with a following action y, then we also have hb(x, y).
(3) If hb(x, y) and hb(y, z), then hb(x, z).
and
(4) A write to a volatile variable (§8.3.1.4) v
synchronizes-with all subsequent reads of v
by any thread (where subsequent is defined according to the synchronization order).
Theorem
Given that thread #1 has called setBoth(...);
once, and that the arguments were non-null, and that thread #2 has observed b
to be non-null, then thread #2 cannot then observe a
to be null.
Informal Proof
- By (1) - hb(write(a, non-null), write(b, non-null)) in thread #1
- By (2) and (4) - hb(write(b, non-null), read(b, non-null))
- By (1) - hb(read(b, non-null), read(a, XXX)) in thread #2,
- By (4) - hb(write(a, non-null), read(b, non-null))
- By (4) - hb(write(a, non-null), read(a, XXX))
In other words, the write of a non-null value to a
"happens-before" the read of the value (XXX) of a
. The only way that XXX can be null, is if there was some other action writing null to a
such that hb(write(a,non-null), write(a,XXX)) and hb(write(a,XXX), read(a,XXX)). And this is impossible according to the problem definition, and therefore XXX cannot be null. QED.
Explanation - the JLS states that the hb(...) ("happens-before") relationship does not totally forbid reordering. However, if hb(xx,yy), then reordering of actions xx and yy is only allowed if the resulting code has the same observable effect as the original sequence.