java多个反序列化同一个对象

时间:2013-02-20 15:18:12

标签: java serialization deserialization

我对Java序列化的语义有疑问:两次反序列化同一个对象实际上在内存中创建了两个实例吗?例如:

    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

代码似乎暗示答案是肯定的。我想知道这种行为是否有意义?

1 个答案:

答案 0 :(得分:3)

是的,反序列化会创建对象的新实例,并且反序列化多次会创建多个实例 - 除非您覆盖反序列化方法并实现某种池化,请参阅here例如