Sunday, February 26, 2012

Serialization of a singleton Object

package designPattern;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

/**
* The Class SingletonObjectSerializing.
* If the Singleton class implements the java.io.Serializable interface, when a singleton is serialized and then deserialized more
* than once, there will be multiple instances of Singleton created. In order to avoid this the readResolve method should be
* implemented.
*/
public class SingletonObjectSerializing {

/**
* The main method.
*
* @param args the arguments
*/
public static void main(String[] args) {
System.out.println("Singleton object: "+SingletonObject.getInstance());

try {
ObjectOutputStream objOut=new ObjectOutputStream(new FileOutputStream("SingletonObject.txt"));
objOut.writeObject(SingletonObject.getInstance());
System.out.println("Singleton object serialized: "+SingletonObject.getInstance());
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}

try {
ObjectInputStream objIn=new ObjectInputStream(new FileInputStream("SingletonObject.txt"));
SingletonObject sinObj=null;
try {
sinObj = (SingletonObject) objIn.readObject();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
System.out.println("Singleton object deserialized: "+sinObj);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}


/**
* The Class SingletonObject.
*/
class SingletonObject implements Serializable{
private static final long serialVersionUID = 1L;

/**
* Instantiates a new singleton object.
*/
private SingletonObject(){
super();
System.out.println("Instantiated..");
}

/** The instance. */
private static volatile SingletonObject instance=new SingletonObject();


/**
* Gets the single instance of SingletonObject.
*
* @return single instance of SingletonObject
*/
public static SingletonObject getInstance(){
return instance;
}

/**
* Read resolve.
* This method is called immediately after an object of this class is deserialized.
* This method returns the singleton instance.
* @return the object
*/
protected Object readResolve() {
return getInstance();
}
}

No comments:

Post a Comment

Thanks for your comments/Suggestions.