11

I am deserializing an object from a file that is 350KB in size, and its taking rather a long time. My computer science TA told me that there is a way to use a Buffered reader along with the ObjectInputStream to greatly increase performance. I however can not find anything about this on Google.

Aymon Fournier
  • 4,323
  • 12
  • 42
  • 59

2 Answers2

25

You use decoration to buffer the input stream. Like this

   InputStream in = ...; // your underlying stream (e.g. FileInputStream)
   ObjectInputStream oin = new ObjectInputStream(new BufferedInputStream(in));

This will ensure that each call to ObjectInputStream does not call the base stream in, such as the OS's file read system call. Instead, each call goes to the buffered input stream, which fetches and caches blocks of data (8K by default), and reads from that. This is faster, since reading from the stream is now a local method call in java, and the method call overhead of a system call is encountered less often. Cache coherence and JIT optimizations also come into play in improving performance.

mdma
  • 56,943
  • 12
  • 94
  • 128
  • `ObjectInputStream` uses a 1k buffer at least part of the time, so this suggestion won't have as dramatic an effect as suggested here. – user207421 Mar 25 '13 at 04:36
  • @EJP Will this solution be efficient enough for reading Objects as well as lines like `readLine()` method in `BufferedReader` does? – Akash Agarwal Jan 31 '16 at 07:53
2

No but You can use ObjectInputStream(InputStream in) constructor

To create buffered object intput stream by passing BufferedInputStream as argument to above constructor.

Here is example for reading serialized objects from file:

InputStream file = null;
try {
   file = new FileInputStream("Out.test");
   InputStream buffer = new BufferedInputStream(file);
   ObjectInputStream in = new ObjectInputStream(buffer);
   vector = (Vector)in.readObject();
} catch (Exception e) {
   e.printStackTrace();
} finally{
   if(file != null ) {
       file.close();
   }
}

Checkout following link :

http://java.sun.com/docs/books/performance/1st_edition/html/JPIOPerformance.fm.html

YoK
  • 14,329
  • 4
  • 49
  • 67