GC.OSTM
Be aware of memory leaks due to `ObjectStream' usage
Description
This rule flags any case where ObjectStream usage might cause memory leaks.
ObjectStreams are designed to handle cases where the same Object is sent across a connection multiple times. For this reason, ObjectStream classes keep a reference to all objects written or read until the `reset()' method is called. Those objects will not be garbage collected until `reset()' is called.
Example
package GC;
import java.io.*;
public class OSTM {
public void writeToStream(ObjectOutputStream os, String s)
throws IOException {
os.writeObject (s);
}
}
Repair
Use `reset()' of ObjectOutputStream or InputStream class's method to clear the list of Objects written to the Stream. Or, use DataStreams instead of ObjectStreams in terms of Strings or byte arrays for optimal performance.
package GC;
import java.io.*;
public class OSTM {
public void writeToStream(ObjectOutputStream os, String s)
throws IOException {
os.writeObject (s);
os.reset(); // prevents memory leaks.
}
}
|