Using ObjectOutputStream, how can I use writeObject() to write the same object twice, so on the other end readObject() will read two separate objects, not two references to the same object?

Tim Rohaly

Java's serialization mechanism keeps track of which objects were written to an ObjectOutputStream; when an object is written for the second time a object handle is sent in place of the actual object. This makes the serialization protocol more efficient and allows circular references to be properly dealt with.

This algorithm poses a problem if you send an object, make a change to that object, then try to send it again; the receiving end will not read the changed object, it will reconstruct the original object using the object handle.

You can tell the ObjectOutputStream to "forget" about previously serialized objects by invoking the reset() method. Resetting the stream causes the stream to behave as if it were just constructed, without any knowledge of what was written to the stream prior to the reset(). You should use this method only when required, otherwise you will end up serializing far more data than necessary.