JavaMemoryModel: semantics and optimization of final fields

From: Bill Pugh (
Date: Tue Aug 17 1999 - 12:11:04 EDT

I've been thinking about the semantics of final fields, and the
optimizations we would like to allow on them.

One thing I think we would like to allow is to allow a compiler to
keep the value of final fields cached in registers across
synchronization and function calls (e.g., a acquire/memory barrier
doesn't force you to reload final fields you have cached in
registers). I suspect that a number of compilers do this already
(I'll write a test program to check), even though it isn't allowed by
the old memory semantics.

There are ways you could detect this. If you allow an object to
escape its constructor before its blank finals are set, or if you
have a data race on a SMP with a weak memory model, another thread
could see the default value for the field, and then when looking
again, see the correct value. A synchronization could force it to see
the correct value, but not if you don't have to reload final fields.

I discussed this with the Sun people (and I think with the Dec
people) and people were happy with the idea, although it would mean
that classes that allow objects to escape before assigning to blank
finals would see strange semantics. I forgot to include this in my
trip report.

OK, now does this have any implications for initialization safety?

Say that memory barriers didn't force a reload of memory barriers,
but we don't have initialization safety for final fields. This seems
to be a mismatch. It says you do need to do a memory barrier for
initialization safety of final fields, but also that memory barriers
don't have an effect on final fields.

Furthermore, until we are very careful/convoluted with our semantics,
we would get semantics that said that if the first load of a final
field by a thread wasn't synchronized properly (i.e., wasn't
initialization safe), than all future references to that field from
that thread might see the incorrect default value, even if they were
initialization safe. This would have all sorts of nasty security

So, based on this reasoning, I'm drawn more strongly to the idea
that, at least, we should guarantee initialization safety for final
fields. Doing more than that is a different issue. I still want to
see numbers on the cost of making final fields (or all fields)
initialization safe. Some of the people at DEC are looking into that
and may have some numbers shortly; I'm also starting to think about
that (although my numbers will be a while in coming).

JavaMemoryModel mailing list -

This archive was generated by hypermail 2b29 : Thu Oct 13 2005 - 07:00:18 EDT