[jmm-dev] The JSR-133 Cookbook and final fields

Hans Boehm boehm at acm.org
Tue Nov 15 18:44:01 UTC 2016


I think this is actually OK for final fields, since no other thread can
write them, and hence reads in the constructor can't really see a write by
another thread.

I continue to believe that we should not generalize the final field
behavior to non-final fields, at least not without generalizing the
constructor barrier to also include LoadStore. Which I think means we're
kind of in agreement. If we did so, and programmers took advantage of that,
it would also mean that constructor() { non_final_field = 0; assert
non_final_field == 0; } could reasonably fail, which seems bad.

Generalizing final field memory ordering to non-final fields also has
optimization consequences on the reader side that we're still struggling
with for C++.

For example, on any flavor of ARM or Power, in

tmp = x;
...
tmp2 = y;
if (tmp == tmp2) {
    tmp3 = tmp2.a;
}

the last assignment can no longer be replaced by tmp3 = tmp.a, because that
wouldn't preserve ordering between the load of y and that of a. (I suspect
that such a replacement can be beneficial if the branch can be correctly
predicted, since tmp may be available earlier.)

Presumably similar rules already apply to final field optimization.  I have
no idea whether existing Java compilers actually make such distinctions.

On Tue, Nov 15, 2016 at 5:53 AM, Andrew Haley <aph at redhat.com> wrote:

> It's been pointed out to me that my example doesn't have a final
> field!  It would perhaps have been better not to provide an example,
> so rather than muddy the water any further I'll let the question
> stand.
>
> Andrew.
>


More information about the jmm-dev mailing list