JRR
JRR

Reputation: 6152

java multiple deserialization of the same object

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?

Upvotes: 1

Views: 2308

Answers (1)

radai
radai

Reputation: 24202

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

Upvotes: 3

Related Questions