1

I have a question about the semantics of Java serialization: does deserializing the same object twice actually create two instances in memory? For instance:

    ByteArrayOutputStream ba = new ByteArrayOutputStream();
    ObjectOutputStream oos = new ObjectOutputStream(ba);

    LinkedListNode tail = new LinkedListNode(null);
    LinkedListNode n1 = new LinkedListNode(tail);

    oos.writeObject(n1);
    oos.flush();

    ByteArrayInputStream bi = new ByteArrayInputStream(ba.toByteArray());
    ObjectInputStream ois = new ObjectInputStream(bi);
    LinkedListNode r1 = (Node)ois.readObject();

    ByteArrayInputStream bi2 = new ByteArrayInputStream(ba.toByteArray());
    ObjectInputStream ois2 = new ObjectInputStream(bi2);
    LinkedListNode r2 = (Node)ois2.readObject();

    System.out.println("r1 == r2 " + (r1 == r2)); // prints false
    System.out.println("r1.next == r2.next " + (r1.next == r2.next)); // prints false

The code seems to imply that the answer is yes. I am wondering if this behavior makes sense?

JRR
  • 6,014
  • 6
  • 39
  • 59
  • 1
    Yes and yes. Deserializing means that you will *create* an object based on the serialized data, so it has to be a new instance. Also, it would be *very bad* if you deserialize data and generate the same object with the same *address location* (thus generating memory leaks). – Luiggi Mendoza Feb 20 '13 at 15:20

1 Answers1

3

yes, deserialization creates a new instance of your object, and deserializing several times will create several instances - unless you override the deserialization methods and implement some sort of pooling, see here for example

Community
  • 1
  • 1
radai
  • 23,949
  • 10
  • 71
  • 115