views:

105

answers:

2

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.

+9  A: 

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
+1  A: 

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
Might want a `try {` after the `file` declaration line, and a `} finally { file.close(); }` instead of `in.close();`.
Tom Hawtin - tackline
This code definitely won't compile, since in the `finally` block, `file` isn't declared.
uckelman
@uckelman Now code should compile. Earlier I had put in ref code but didn't test/compile same.
YoK