Avner Levy Avner Levy - 4 months ago 18
Java Question

How to reset ObjectInputStream objects graph cache to avoid memory bloat

When loading huge files with ObjectInputStream, all read objects are buffered by stream for object graph resolving.

This cause huge memory overhead which isn't needed in my case (all objects read are interdependent).

Is there an equivalent to the reset() method of ObjectOutputStream which reset this buffer?

Code example:

try (FileInputStream fileInputStream = new FileInputStream(filename);
BufferedInputStream bufferedInputStream = new BufferedInputStream(fileInputStream);
ObjectInputStream objectInputStream = new ObjectInputStream(bufferedInputStream)) {
while (object = objectInputStream.readObject()) {
System.Out.println(object.toString());
}
}



EJP EJP
Answer

It's up to the sender to decide when to break the integrity of sent object graphs, by calling ObjectOutputStream.reset(). Not the receiver.

NB your code doesn't compile, and wouldn't be valid if it did:

while (object = objectInputStream.readObject()) {
}

This should be

try {
    while (true) {
        object = objectInputStream.readObject();
        // ...
    }
}
catch (EOFException exc) {
    // end of stream
}

There is a misconception abroad that readObject() returns null at end of stream. It doesn't. It throws EOFException. It can return null any time you wrote a null.