RE: JavaMemoryModel: Motivation and Semantics for Immutable objects

From: Evan Ireland (eireland@sybase.com)
Date: Mon Oct 20 2003 - 17:58:11 EDT


Doug,

The key issue for me is when implementing subclasses of
java.io.ObjectInputStream, needing a portable API to set the final
fields (as well as one to create an instance without calling the
constructor). Trying to do this without native code (or without
calling JDK-internal private APIs using reflection) is basically
impossible. So much for write-once, run-anywhere :-)

> -----Original Message-----
> From: owner-javamemorymodel@cs.umd.edu
> [mailto:owner-javamemorymodel@cs.umd.edu]On Behalf Of Doug Lea
> Sent: Tuesday, 21 October 2003 1:33 a.m.
> To: eireland@sybase.com
> Cc: jmm
> Subject: RE: JavaMemoryModel: Motivation and Semantics for Immutable
> objects
>
>
> > 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
>
-------------------------------
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