Serialize a Singleton Class

HI,

As we know that Singleton class is a special kind of class which maintains a single instance throughout the application. Mainly we use singleton classes to implement control access services like Connection Pool factory, Service factory etc.

But the question arise is, Can be Serialize/Deserialize a singelton class object. And the answer is YES WE CAN, but that has to handled in the singleton class itself.

To make that class serialize we just have to implement the Serializable interface. But the main thing we have to handle is the Deserialization part of that object.

By default, the deserialization process creates new instance of classes. The below example will show how to customize the deserialization process of a singleton to avoid creating new instances of the singleton.

public class DBFactory implements Serializable {

private static DBFactory singleton = new DBFactory();

private DBFactory() {
// This method returns the singleton instance.

}

public static synchronized getInstnce(){
return singleton;

}

// This method is called immediately after an object of this class is deserialized.
protected Object readResolve() {
// instead of the object we’re on,
// return the class variable singleton

return singleton;

}

}

For Serializable and Externalizable classes, the readResolve method allows a class to replace/resolve the object read from the stream before it is returned to the caller. By implementing the readResolve method, a class can directly control the types and instances of its own instances being deserialized.

PS:  if you depend on readResolve for instance control, all instance fields with object reference types must be declared transient. Otherwise, it is possible for a ANYONE to access(ref) to the deserialized object before its readResolve method is run.


Thanks
R Vashi

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s