We serialize a Singleton object and save into a file Saved.txt. Now from a different jvm if we deserialize then deserialization use reflection and create a object with same instance values saved in the file.But it is a different object, so we get different hashCode.
But if we use readresolve() method in our singleton class then we will get same hashCode.
So the question is how we are getting a same hashCode?
The object we are getting now,should be a new object only not that one which we created at the time of serialization.
When readObject() is called on an ObjectInputStream, it will deserialize the Serializable object from the input stream, and then the readResolve() method will be called on the deserialized object. So even though a new instance of Singleton is deserialized, the invocation of readResolve() on that new object will return the shared instance that was previously made and stored in the static instance field.
This code nicely demonstrates how useless it is to make an instance controlled type serializable.
Try to avoid the Serializable class if you can help it. Definitely avoid the singleton anti-pattern.
The mind is a strange and wonderful thing. I'm not sure that it will ever be able to figure itself out, everything else, maybe. From the atom to the universe, everything, except itself.
Campbell Ritchie wrote:Aren't Oracle going to deprecate serialisation?
I heard they were....
Although articles still abound on the Oracle website about serialisation (one example is this old article here), I have heard "rumblings" that indeed Oracle appears to want to deprecate serialisation, mainly due to security gaps. Some in the tech media are speculating the beginning of it's demise (such as DZone).
To their credit, Oracle did produce documentation warning about serialisation/deserialisation (Secure Coding...).