RE: JavaMemoryModel: Motivation and Semantics for Immutable objects

From: Doug Lea (dl@cs.oswego.edu)
Date: Mon Oct 20 2003 - 08:32:48 EDT


> In regard to serialization of value types with RMI, the notion of
> immutability is of some interest, in particular because the JDK
> provides no standard way for custom-coded serialization classes
> to set final fields (java.lang.reflect.Field.set() throws an
> exception if called to set a final field), and the JDK provides
> no standard way to create an object without calling its constructor.
>

Ignoring the spec issues here that I don't know how to address, there
are some tricks that sometimes apply when you can't use default
deserialization of final fields. They are all on the ugly side, and
trade off some wastage. They might be appropriate when you can live
with having extra fields and possibly slower deserialization. See for
example JSR166 ArrayBlockingQueue.java at:
  http://gee.cs.oswego.edu/cgi-bin/viewcvs.cgi/jsr166/src/main/java/util/concurrent/ArrayBlockingQueue.java

It declares an extra nonfinal field used only to hold the deserialized
state of a final field (the underlying data array), and uses
readResolve during deserialization to create a new object using an
internal constructor that sets final fields to the values of the
nonfinal ones of deserialized form that will then be thrown away and
replaced by new object.

If you have multiple fields of this form, and/or want to apply to
multiple subclasses, you can define internal SerializationProxy
objects so only need a single "wasted" reference in main objects.

(If you think this is too sleazy to even tell people, blame me. If you
think it is a cool hack, credit Josh Bloch for discovering the basic
idea here :-)

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



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