Let say we have the following singleton class:
public class ConnectionFactory implements Serializable {
private static ConnectionFactory INSTANCE;
private ConnectionFactory() { }
public static ConnectionFactory getInstance() {
if (INSTANCE == null) {
synchronized(ConnectionFactory.class) {
if(INSTANCE == null)
INSTANCE = new ConnectionFactory();
}
}
return INSTANCE;
}
}
Now we have the main class like below for serialising and deserializing objects:
public static void main(String[] args) throws FileNotFoundException, IOException, ClassNotFoundException {
ConnectionFactory INSTANCE=ConnectionFactory.getInstance();
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("connFactory.ser"));
oos.writeObject(INSTANCE);
oos.close();
// Here I am recreating the instance by reading the serialized object data store
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("connFactory.ser"));
ConnectionFactory factory1 = (ConnectionFactory) ois.readObject();
ois.close();
// I am recreating the instance AGAIN by reading the serialized object data store
ObjectInputStream ois2 = new ObjectInputStream(new FileInputStream("connFactory.ser"));
ConnectionFactory factory2 = (ConnectionFactory) ois2.readObject();
ois2.close();
// Let's see how we have broken the singleton behavior
System.out.println("Instance reference check->" +factory1.getInstance());
System.out.println("Instance reference check->" +factory2.getInstance());
System.out.println("=========================================================");
System.out.println("Object reference check->" + factory1);
System.out.println("Object reference check->" + factory2);
}
So if we execute above code we will get following behaviour:
"it has created two objects and one static reference for INSTANCE. That means if we read the serialized format of a singleton object multiple times, we will create multiple objects. This is not what a singleton object is supposed to do. So can we avoid i?, Yes, we can."
To avoid multiple instances of singleton class we will use following method provided by serialization:
private Object readResolve() throws ObjectStreamException {
return INSTANCE;
}
This will prevent the creation of multiple instances of a singleton class.