JavaMemoryModel: Immutablity and Final Fields

From: David Holmes (
Date: Sun Feb 25 2001 - 19:31:11 EST

Again relating to the "Semantics of MultiThreaded Java" I would like to
clarify the semantics of final fields with regard to constructing immutable
objects such as String.

The requirement is that all fields of String which "define" the immutable
data, must be declared final - in the case of String this would be char[]
value, int offset and int count. Any logically immutable data that is lazily
calculated from the immutable data need not be (and can not be) declared
final, nor need it be declared volatile, because the immutable data itself
is guaranteed to be visible with the assigned values from the constructor.
So for example, in String the cached hash value is fine as a non-final,
non-volatile field.

Conversely, any immutable object whose immutable data is not set at
construction time and so which can't be declared final, is not a "safe"
immutable object. Such objects must use either volatile fields, or employ
normal synchronization. This implies that any factory method that
"initialises" an "immutable" object after construction, can not return an
object that can be safely shared without synchronization. Of course, we can
make such an object "safe" by making the shared reference to the object
volatile, or by assigning during static initialization - the former incurs a
cost on every access, while the latter is not always practical. (And any
object is "safe" when accessed via a final field.)

I'm just trying to get a feel for what the new semantics mean for factory
methods and whether there are simple techniques that will make all existing
factory methods of this type "safe"

David Holmes
JavaMemoryModel mailing list -

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