ShenandoahOptimizeFinals is an illegal optimization

Aleksey Shipilev shade at redhat.com
Wed Oct 18 13:06:40 UTC 2017


On 10/18/2017 03:01 PM, Roland Westrelin wrote:
> 
>> Which is legal in Java, I think. The instance of TestFinal had leaked from the constructor, and
>> therefore no rule forbids seeing 0 in tf.field when read. This is similar to "Example 17.5.3-1.
>> Aggressive Optimization of final Fields" in JLS, e.g. the write happens "outside of" constructor as
>> far as the prematurely published instance of TF is concerned. Shenandoah optimization make that
>> allowed result visible.
> 
> In a sequential program? Whichever way we read the spec, that doesn't
> sound reasonable to me.

Yes, in a sequential program, see Example 17.5.3-1 from here:
  https://docs.oracle.com/javase/specs/jls/se9/html/jls-17.html#jls-17.5.3

Final fields are special like that: you are not guaranteed to see the writes to final fields that
happen unsafely (outside of constructor, or observed via premature publication). Because optimizers
are allowed to trust final field values and inline their values as they see fit. GCs can also use
that to show from-copy values without remorse.

Breaking the JLS requirements does lead to counter-intuitive results :)

>> I think it makes sense to verify that -ShenandoahOptimizeFinals does not fail so that we have a
>> workaround, but as far as the optimization itself is concerned, I still believe it is legal.
> 
> It breaks existing code. You can't use inner classes and safely refer to
> fields from the outer class anymore. It doesn't sound like we want to
> leave this on.

Tough call. Seems like the same thing as with TrustFinalNonStaticFields -- probably we want to
condition ShenandoahOptimizeFinals on TrustFinalNonStaticFields? And, can we at trust @Stable fields
with this optimization?

Thanks,
-Aleksey




More information about the shenandoah-dev mailing list