Tuesday, June 9, 2015

Serialization problem with Singleton

In previous example we have seen the basics of singleton. In this example we will see how Serialization can effect the Singleton design pattern.

Sometimes in distributed systems, we may need to implement Serializable interface in Singleton class so that we can store it's object state in a file system and retrieve it at later point of time. Let's take an exammple of Clipboard class which implements Serializable interface.

Clipboard.java


TestClipboard.java


Output :
c1 hashCode = 28117098
c2 hashCode = 13495805

From the above hashCode output we can see the intent of singleton pattern is simply blown up, to overcome this problem we need to provide the implementation of readResolve() method as shown below.


Now if u see the hashCode output, it will be same.

The readResolve method is invoked by serialization if the method exists and it would be accessible from a method defined within the class of the object being serialized. Thus, the method can have private, protected and package-private access. Subclass access to this method follows java accessibility rules.

Classes that need to designate a replacement when an instance of it is read from the stream should implement this special method with the exact signature - ANY-ACCESS-MODIFIER Object readResolve() throws ObjectStreamException;

No comments:

Post a Comment