Thursday, January 3, 2008

Singleton - Serialization (Read) problem

Singleton Class that we discussed in Guaranteed Single Object Model post is almost guaranteed to be singleton but the problem comes when we are having solution environments with serialized objects.

Problem Description: There is a singleton class with object A, now this object is serialized on a stream, now what happens if we deserialize the object from the stream will there be more than one (single) objects? if yes how we can handle this issue.

Solution: yes indeed there will be two instances (or as many objects are read from the stream), we can't handle this issue in constructor or getInstance method as no calls are made by JVM for reconstructing an object from deserialization. To handle this issue Java provide users an option to define a protected readResolve method which is guaranteed to be called just after the deserialization and before reconstruction of the object.

Final Singleton Class

public class MySingleton{
private static MySingleton instance=null;
private MySingleton(){
//no code required - or any other initialisation code
}
public static synchronized MySingleton getInstance(){
if(instance==null){
instance=new MySingleton();
}
return instance;
}
public Object clone() throws CloneNotSupportedException{
throw new CloneNotSupportedException();
}

//method guaranteed to be called after deserialization and before object reconstruction
protected Object readResolve() throws ObjectStreamException{
return instance;//return the singleton object
}
//any other methods or code
}