how do you avoid creating a new instance while deserializing an object?

Here is my code which serializes, and deserializes.

FileOutputStream fos = new FileOutputStream(“myserial1.txt”);
ObjectOutputStream oos = new ObjectOutputStream(fos);
Elvis e = Elvis.getInstance();
System.out.println(” e = “+e.getInstance());

oos.writeObject(e);

System.out.println(“Serialization done.”);
FileInputStream fis = new FileInputStream(“myserial1.txt”);
ObjectInputStream ois = new ObjectInputStream(fis);
Elvis el = (Elvis) ois.readObject();
System.out.println(” el = “+el.getInstance());

I See both e and e1 are priting the same reference, and constructor is invoked only once.

http://stackoverflow.com/questions/21361137/deserializing-a-singleton-in-java

Leave a Reply