O'Reilly logo

Java I/O by Elliotte Rusty Harold

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Performance

Serialization is often the easiest way to save the state of your program. You simply write out the objects you’re using, then read them back in when you’re ready to restore the document. There is a downside, however. First of all, serialization is slow. If you can define a custom file format for your application’s documents, using that format will almost certainly be much faster than object serialization.

Second, serialization can slow or prevent garbage collection. Every time an object is written onto an object output stream, the stream holds on to a reference to the object. Then, if the same object is written onto the same stream again, it can be replaced with a reference to its first occurrence in the stream. However, this means that your program holds on to live references to the objects it has written until the stream is reset or closed—which means these objects won’t be garbage-collected. The worst-case scenario is when you keep a stream open as long as your program runs and write every object you create onto the stream. This prevents any objects from being garbage-collected.

The easy solution is to avoid keeping a running stream of the objects you create. Instead, save the entire state only when the entire state is available, and then close the stream immediately.

If this isn’t possible, you have the option to reset the stream by invoking its reset() method:

public void reset() throws IOException

reset() flushes the ObjectOutputStream object’s internal cache of the ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required