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?

1
  • 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). Commented Feb 20, 2013 at 15:20

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.