JavaMemoryModel: Semantics of final and fixing the immutable String problem

From: Bill Pugh (
Date: Tue May 15 2001 - 21:54:45 EDT

> > In the string case, the reference to the array of characters and the
> > offset have to be final.
> Surely the length field must be final too, otherwise the wrong number of
> characters may be read, or the wrong value returned from length()?

yes. In general, to get special semantics for immutable objects, you must
declare all of their fields to be final.

> In the context of the example it is hard to see how the String and
> StringBuffer classes would really be implemented. I would expect that using
> copy-on-write, the String would be given a new char[] rather than the
> StringBuffer (otherwise the String would keep alive the entire StringBuffer
> char[], which could be much bigger than the string itself. In that context
> the char[], length and offset can not be final because they are mutable
> values. So it is difficult to view this example as a realistic example of
> either the problem or the solution.

You can just take the current String and StringBuffer implementation
and change all of the fields in the String class to be final. It is perfectly
OK for the string to have a final ref to the char[] that is also being used
by the StringBuffer.

The fact that a String can keep a much larger StringBuffer alive is an artifact
of the current implementation. It would certainly be possible to
implement things so that converting a StringBuffer to a String only
shared the char[] if the String used at least one half of the char[].

> In general, I return to my earlier statement, that it seems to me that all
> of the fields of the immutable object must be declared final. That seems
> overly restrictive given the use of lazy initialisation and the problems of
> final fields when used with serialization and cloning.

We have been unable to devise any other scheme that would allow
efficient execution on an Alpha SMP, a DSM system, or any other
system with a similarly weak memory model. But we are open to new

        Bill Pugh
JavaMemoryModel mailing list -

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