[jmm-dev] final reads/writes

Jeremy Manson jeremymanson at google.com
Sun Feb 9 16:34:32 PST 2014


So, to reiterate my previous postings (too): I used to believe that a
memory model should provide extra latitude for optimizations in these
cases, but now I'm perfectly happy with not saying anything.  We do need to
talk about the safety guarantees, and anything that VM developers can do
given those safety guarantees is fine.

My mind was changed when we tried hoisting final loads in Hotspot, and got
a percent or so speedup, but threw some code into infinite loops.

I think it is just too confusing for users if they change the value of a
field, but subsequent loads - regular, same-thread loads - don't see the
changed value.

Compilers should only do a loop invariant hoist if they can prove that the
value being hoisted is loop invariant.

Now, if you can prove that the value doesn't change, then you can certainly
do the optimization.  But in that case, the final annotation is a hint, not
a proof.  I'm not sure that the JMM needs to say anything about that.

Jeremy


On Sun, Feb 9, 2014 at 7:31 AM, Doug Lea <dl at cs.oswego.edu> wrote:

> Continuing my quest to introduce issues early and often...
>
> Assuming that we go ahead with the idea of ensuring a release fence
> upon construction (normally free, because piggybacked with those
> required anyway for object headers), rather than only in the presence
> of final fields, do we need to say anything special about final fields?
>
> I can't quite rule it out. Thoughts welcome.
>
> Background: Optimizers like to remove unnecessary reads
> (and computations based on them). It seems that any plausible
> memory model will allow cases based on the idea that if you can
> identify a readsFrom source for a value, and you've already
> read it, then no additional ordering constraints could
> force you to re-read, so don't.
>
> In a more ideal world, "final" would allow a more aggressive
> version: If you've  (implicitly) identified ANY readsFrom source,
> that's good enough, because there is only one. Unfortunately, "final"
> doesn't strictly mean this in JVMs -- there are cheats
> sometimes allowing further updates to final variables. And in
> practice JVMs are conservative enough to allow those cheats
> to work, despite some wording in the JSR133 JMM allowing them
> not to work.
>
> Additionally, JDK8 hotspot introduced the @Stable annotation
> that in essence says: if the value is nonnull, then it is the final
> written value. And similar cases arise in which there may be
> bookkeeping to track "Freeze after writing" status
> (https://www.cs.indiana.edu/cgi-bin/techreports/TRNNN.cgi?trnum=TR710),
> and a possible JDK9 proposal for explicitly "frozen" arrays.
>
> The question at hand is: Does a memory model itself need to say
> anything explicitly about any of these?
>
> -Doug
>
>


More information about the jmm-dev mailing list