final transient fields serialization

Rémi Forax forax at univ-mlv.fr
Tue Nov 10 07:30:26 UTC 2009


Le 10/11/2009 00:38, David M. Lloyd a écrit :
> On 11/09/2009 03:30 PM, Pawel Veselov wrote:
>> Hi,
>>
>> it again caught my attention, and I though that may be there is
>> something that can be done about this.
>> The issue is obvious -- having 'final transient' instance fields makes
>> little sense if the object is ever serialized.
>> Logically, there may be perfect reasoning behind making an instance
>> field final, as well as transient, in which case there is then no
>> mechanism to reinitialize this field on object deserialization.
>
> I've used final transient fields before to hold values which are not 
> relevant on the remote side (and thus can be null or 0), but point 
> taken...
>
>> It seems that it would be nice if either the final fields were
>> initialized in a separate block that would be executed on
>> deserialization, or if readObject() could set them. After all you can
>> have a code block that sets the final fields. Not sure how feasible that
>> is, but IMHO, that is a short coming.
>
> One possible problem with this is that changing a final field might 
> have some JMM implications (case in point, CopyOnWriteArrayList uses 
> sun.misc.Unsafe#putObjectVolatile() to reinitialize the transient 
> final Lock field, though I don't see anywhere that ObjectInputStream 
> itself takes such precautions; one would think that 
> java.lang.reflect.Field would take care of this for you, but perhaps 
> it does not).

It does :)
Chnaging a volatile or a final field by reflection is done with a 
put...Volatile().

[...]

>
> - DML

Rémi



More information about the core-libs-dev mailing list