views:

69

answers:

3

Why is the table field of Hashtable serialized, although it is marked as transient?

+1  A: 

Because it has writeObject() and readObject() implemented (in private methods), with which it can control how it is to be serialized and deserialized. It's around line 800 in Java 1.6 source code.

Check this Sun advanced serialization guide for details how it works "under the hoods".

BalusC
Thanks a lot. Can you tell me also why it is declared transient.
ppoliani
So that it does not "automatically" get serialized which would cause data duplication.
BalusC
It ok i'm covered, thanks again!
ppoliani
+1  A: 

If you look at the source code of the Hashtable class (at least in 1.6), the Entry[] table is marked as transient but the class implements writeObject(), in which it writes the contents of the entry table to the ObjectOutputStream.

Thus the contents of the Hashtable are always serialized.

Why did they choose to implement it this way? Likely to have control over how the array is serialized.

matt b
+6  A: 

It is marked as transient because it is unsafe to use the default serialization scheme on the Entry array. Rather, when a Hashtable is deserialized, the keys in the table must be rehashed and the entries must be added to slots according to the new hashcode values. This is necessary because the keys may have different hashcodes after deserialization ... for a variety of reasons. This work will be done by Hashtable's readObject() method.

Stephen C
More generally it cuts the dependency between implementation and serialisation format, so that the former can change whilst the latter stays compatible. You can see ugly hacks where serialisation wasn't thought about.
Tom Hawtin - tackline