Video in progress
If you keep sending one modified object over a long-lived `ObjectOutputStream`, why does the other side see the old value, and why does memory keep growing?
ObjectOutputStream remembers every object it writes in a handle table and next time sends only a reference. The change doesn't go out, and the table isn't cleared until the stream is closed. The fix is reset() or writeUnshared().
📖 Answer
var out = new ObjectOutputStream(socket.getOutputStream());
Status st = new Status();
for (int i = 0; i < 3; i++) {
st.progress = i * 50;
out.writeObject(st); // the 2nd and 3rd time it is only a reference meaning "the previous object #0"
}
The receiver gets the same object three times, with progress = 0. This is by design: serialization has to preserve cycles and shared references in an object graph, so it remembers "I already sent this object".
The memory problem comes from the same place. The table holds a strong reference to every written object. If you send millions of messages through a socket that stays open for days, none of them can be collected by the GC. On the receiving side, ObjectInputStream keeps the objects it has read in the same way, so the leak is on both ends.
The fix:
out.writeObject(st);
out.reset(); // clears the table, the next object is written in full
After reset() the class descriptors are also resent, so calling it after every message raises the traffic a bit; it is usually called every N messages or after each "logical packet".
writeUnshared(obj) writes only the top-level object as new; the fields inside it can still end up as shared references. So if the inner state has changed, it is not a complete solution.
Not knowing this behavior is the classic cause of "the data doesn't update" and a slow OutOfMemoryError in old RMI and socket-based systems.
Sign up to mark studied questions and save your progress.