[concurrency-interest] Concurrent Serialization Pattern

Peter Jones peter.jones at sun.com
Fri Sep 15 11:27:09 EDT 2006


>>>> According to my reading of the serialization spec it *should*
>>>> have a null value. transient fields don't get serialized, unless
>>>> you custom serialize them. So a transient final field should have
>>>> its default initialized value when readObject is invoked.
> 
> I'm not entirely content with empirical discovery for understanding
> JMM issues, and the serialization spec *does* seem to give an
> expectation of seeing the default value for the transient final
> field: "The. values of every field of the object whether transient
> or not, static or not are set to the default value for the fields
> type" (sec 3.4). Though it doesn't explicitly mention "final"
> fields.

That assertion is accurate even for final fields.  If you reflect upon
a transient final instance field of a deserialized object-- and it
hasn't been set through privileged magic-- you will see the default
value (null, 0, or false).

The case David cited is that if a final field's initializer is a
compile-time constant expression (JLS3 15.28), so the field is a
constant variable (JLS3 4.12.4), a field access expression for it will
be compiled to the compile-time constant value (i.e. inlined) rather
than to a bytecode to access the field at runtime (JLS3 13.4.9)-- so a
non-reflective field access won't "see" the default value that it has.

> Since "Fields declared as transient or static are ignored by the
> deserialization process" according to the ObjectInputStream javadoc,
> I guess it makes sense for "ignored" to mean that transient fields
> are left in the "completely initialized" state that
> Class.newInstance() leaves them in (JLS 17.5).

No, Class.newInstance() invokes the default constructor and thus
executes instance field initializers, unlike deserialization.

> So the guarantee for never seeing the transient final field's
> default value is provided by JLS 16 and 17.5.  Maybe an explicit
> statement about transient final fields would help in the
> serialization spec and in the ObjectInputStream API javadoc?
> 
> I wonder why there's such an expectation that transient final fields
> would have their default value after deserializing.  Do older
> compilers or JVMs behave differently?  Or is it just the clarity of
> the docs, esp. the serialization spec sec 3.4?

There is no such guarantee-- it just can seem that way with
constant-initialized final fields.  Documentation could certainly be
improved to reduce confusion in this area; there is an open RFE about
related points:

	http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6252102

-- Peter


More information about the Concurrency-interest mailing list