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(){
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

1 comment:

buddy said...

Nice post , just to add
While writing Singleton class we need to consider many points e.g.
1) Lazy initialization
2) Early initialization
3) Serialization
4) Many ClassLoaders
5) Cloning

to tackle all above problem best way is to use JAVA 5 Enum functionality and write Singleton using Enum like below.
public enum Singleton {

public static void hi(){

Why String is immutable in Java