Re: JavaMemoryModel: Serialization and final fields

From: Joshua Bloch (jbloch@eng.sun.com)
Date: Wed Aug 25 1999 - 06:18:22 EDT


Bill,
 
   Yes, it's amazing how much of the spec is affected by serialization. It's always been apparent to me that "readObject" and its kin were de facto constructors. They should have been real, explicit constructors. We get bitten by this in various guises from time to time (e.g., the security bug that allowed you to create mutable Strings).

> it is _impossible_ to set final fields. Does anyone disagree?

   Who knows? The serialization spec doesn't really say one way or the other, though it implies that one can't set them. Step 10 of the deserialization protocol (from Section 3.1 of the Serialization spec):

> 10. An instance of the class is allocated. The instance and its handle are added to
> the set of known objects. The contents restored appropriately:

   What does "is allocated" mean? Is a constructor called? Is the remainder of the step executed from within the same constructor? Who knows.

> This might prove to be a drawback to using final to handle the immutability problem;
> sometimes you can't use it because you want to have your own custom Serialization
> scheme.

    The truth is, you almost always want your own custom serialization scheme. Default serialization is far too confining (it holds you to your original representation, in fact making it part of your public API), slow, and dangerous attackers can deserialize arbitrary byte streams to produce compromised objects).

    I'm not sure exactly what to do about this. I can think of no solution that preserves the sanctity of final and the identity of the deserialized object. I suppose we could adopt a solution that was less dependent on final (like complete initialization safety). But this doesn't exactly solve the problem. It just sweeps it under the rug.
.

                                Josh

P.S. In case you're not already physically ill, note that the methods System.setErr, setIn and setOut are specified to set the values of the fields System.err, in and out, all of which are specified to be final. Yeccccch

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



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