Consider I have a Singleton class defined as follows.
public class MySingleton implements Serializable{
private static MySingleton myInstance;
private MyS
Here below is my Singleton class that implements Serializable interface. Mark that it contains readResolve() method also.
import java.io.Serializable;
public class Singleton implements Serializable {
private static Singleton singleton = new Singleton( );
public int i = 1;
private Singleton() { }
public static Singleton getInstance( ) {
return singleton;
}
public Object readResolve() {
return getInstance( );
}
public static void main(String[] args) {
Singleton s1 = getInstance();
System.out.println(s1.hashCode());
Singleton s2 = getInstance();
System.out.println(s2.hashCode());
}
}
Below is the class that will first serialize and then deserialize the above class. Here deserialization takes place two times, but both time only one instance will be created because of readResolve() method.
public class SingletonSerializableDemo {
static Singleton sing = Singleton.getInstance();
static Singleton s1 = null;
static Singleton s2 = null;
public static void main(String[] args) {
try {
FileOutputStream fileOut =
new FileOutputStream("E:/singleton.ser");
ObjectOutputStream out = new ObjectOutputStream(fileOut);
out.writeObject(sing);
out.close();
fileOut.close();
System.out.println("Serialized data is saved");
FileInputStream fileIn1 = new FileInputStream("E:/singleton.ser");
FileInputStream fileIn2 = new FileInputStream("E:/singleton.ser");
ObjectInputStream in1 = new ObjectInputStream(fileIn1);
ObjectInputStream in2 = new ObjectInputStream(fileIn2);
s1 = (Singleton) in1.readObject();
s2 = (Singleton) in2.readObject();
System.out.println(s1.hashCode() + " "+ s1.i);
s1.i = 10;
System.out.println(s2.hashCode() + " "+ s2.i);
in1.close();
in2.close();
fileIn1.close();
fileIn2.close();
}catch(Exception i) {
i.printStackTrace();
}
}
}
And the output will be:
Serialized data is saved
21061094 1
21061094 10
Conclusion: Singleton class can also be serialized by keeping readResolve() method in the Singleton class.