JavaMemoryModel: Immutablity and Final Fields

From: Jeremy Manson (jmanson@cs.umd.edu)
Date: Sun Feb 25 2001 - 22:15:23 EST


> 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.)

Assuming that everything is done more-or-less perfectly, then when you
have finished initializing the field, you can do what you said originally
and make the shared reference to the object volatile. You can then read
that reference *once* in the reader thread and copy it to a non-volatile
local. After that, use the non-volatile local instead of the shared
volatile. You only need to perform the memory barrier once, after all.

Unless I misunderstand your question. Or that is impractical, too.

                                        Jeremy
-------------------------------
JavaMemoryModel mailing list - http://www.cs.umd.edu/~pugh/java/memoryModel



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