Consider I have a Singleton class defined as follows.
public class MySingleton implements Serializable{
private static MySingleton myInstance;
private MyS
This may be a familiar solution but just in case for reference.
public class ConnectionFactory implements Serializable {
//Static variable for holding singleton reference object
private static ConnectionFactory INSTANCE;
/**
* Private constructor
*/
private ConnectionFactory() {
}
/**
* Static method for fetching the instance
*
* @return
*/
public static ConnectionFactory getIntance() {
//Check whether instance is null or not
if (INSTANCE == null) {
//Locking the class object
synchronized (ConnectionFactory.class) {
//Doing double check for the instance
//This is required in case first time two threads simultaneously invoke
//getInstance().So when another thread get the lock,it should not create the
//object again as its already created by the previous thread.
if (INSTANCE == null) {
INSTANCE = new ConnectionFactory();
}
}
}
return INSTANCE;
}
/**
* Special hook provided by serialization where developer can control what object needs to sent.
* However this method is invoked on the new object instance created by de serialization process.
*
* @return
* @throws ObjectStreamException
*/
private Object readResolve() throws ObjectStreamException {
return INSTANCE;
}
}
Testing the code
public class SerializationTest {
public static void main(String[] args) {
ConnectionFactory INSTANCE = ConnectionFactory.getIntance();
try {
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("connectFactory.ser"));
oos.writeObject(INSTANCE);
oos.close();
ObjectInputStream osi = new ObjectInputStream(new FileInputStream("connectFactory.ser"));
ConnectionFactory factory1 = (ConnectionFactory) osi.readObject();
osi.close();
ObjectInputStream osi2 = new ObjectInputStream(new FileInputStream("connectFactory.ser"));
ConnectionFactory factory2 = (ConnectionFactory) osi2.readObject();
osi2.close();
System.out.println("Instance reference check->" + factory1.getIntance());
System.out.println("Instance reference check->" + factory2.getIntance());
System.out.println("===================================================");
System.out.println("Object reference check->" + factory1);
System.out.println("Object reference check->" + factory2);
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
Output
Instance reference check->com.javabrains.ConnectionFactory@6f94fa3e
Instance reference check->com.javabrains.ConnectionFactory@6f94fa3e
===================================================
Object reference check->com.javabrains.ConnectionFactory@6f94fa3e
Object reference check->com.javabrains.ConnectionFactory@6f94fa3e