Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Semantics of final Fields in JMM

Here [http://docs.oracle.com/javase/specs/jls/se7/html/jls-17.html#jls-17.5][1]

it says:

Given a write w, a freeze f, an action a (that is not a read of a final field), a read r1 of the final field frozen by f, and a read r2 such that hb(w, f), hb(f, a), mc(a, r1), and dereferences(r1, r2), then when determining which values can be seen by r2, we consider hb(w, r2). (This happens-before ordering does not transitively close with other happens-before orderings.)

What do they want to say here? I understand that r2 is just a read of the final field value which was read by r1, so it is quite clear that hb(w, r2), becuase r1 read correct version of this variable, because the value was frozen by f. Or do they mean something different? Much deep? Also what do they want to say that this hb ordersing does not "transitively close" with other hb ordersings?

like image 547
user3914448 Avatar asked Sep 30 '22 23:09

user3914448


1 Answers

The lone fact that r1 read a value written by w doesn't even mean that hb(w, r1), let alone hb(w, r2). It is the other way around: if there is a happens-before relationship between w and r1, then the JMM guarantees what value will be observed; otherwise there is no guarantee. If r1 does observe the value from w, that's just a coincidence and does not post hoc induce a happens-before relationship.

The best way to imagine a poignant example where this matters is the use case of safe publishing through a data race. A reference to a String is written to a non-volatile field, without synchronization, and that field is then dereferenced from another thread. If the thread happens to observe the String (there is no guarantee that it will), there is a guarantee that the thread will see the String in a consistent state.

Without the special provision of the extra happens-before which is considered only in the precise case described by your quote, there would be no guarantee that the String will be observed intact.

what do they want to say that this hb ordersing does not "transitively close" with other hb ordersings?

Normally, hb(a,b) and hb(b,c) imply hb(a,c), but this transitivity does not apply to the special happens-before existing due to field freezes. These special happens-before's have their own "namespace".

like image 55
Marko Topolnik Avatar answered Oct 17 '22 21:10

Marko Topolnik