Serialization can prevent garbage collection and consequently induce memory leaks. Every time an object is written to a stream, a reference (or handle) to the object is retained by a table maintained by ObjectOutputStream
. If the same object (regardless of its contents) is written out to the same stream again, it is replaced with a reference to the originally cached object (recall that ObjectOutputStream
maintains a live reference to an object after it is written for the first time). The garbage collector cannot reclaim the memory associated with new objects as it cannot deal with collect live references.
Noncompliant Code Example
...