1

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());
  }
}
Community
  • 1
  • 1
Avner Levy
  • 6,601
  • 9
  • 53
  • 92

2 Answers2

4

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.

user207421
  • 305,947
  • 44
  • 307
  • 483
  • 1
    so this means you should never use ObjectInputStream.reset() ? – Mark Y. Apr 30 '13 at 05:10
  • @MarkY. `ObjectInputStream.reset()` is inherited from [`InputStream.reset()`](https://docs.oracle.com/javase/8/docs/api/java/io/InputStream.html#reset--), which does nothing except throw an `IOException`, so you certainly shouldn't use it. – user207421 Jul 18 '16 at 04:45
0

Hmm it seems you need to use some sort of lazy loading techniques where you only load necessairy components of the object graph, not everything.

gerrytan
  • 40,313
  • 9
  • 84
  • 99