Course contentsShow
← Java
Lesson 2120 of 2,87042. SerializationFree lesson

Closing Streams and Resource Management

Learn proper cleanup of ObjectOutputStream and ObjectInputStream using try-with-resources.

Closing Streams and Resource Management

What You'll Learn

You'll learn how to properly clean up ObjectOutputStream and ObjectInputStream using try-with-resources to prevent resource leaks.

Why Closing Streams Matters

When you work with ObjectOutputStream and ObjectInputStream, you're dealing with system resources—file handles, network connections, or memory buffers. If you forget to close these streams, those resources stay locked, potentially causing memory leaks, file corruption, or preventing other programs from accessing the same files.

Think of it like borrowing a book from the library. If you never return it, others can't use it, and eventually the library runs out of books. Closing streams is how you "return the book."

The Old Way (Manual Closing)

Before Java 7, you had to manually close streams in a finally block:

ObjectOutputStream out = null;
try {
    out = new ObjectOutputStream(new FileOutputStream("data.ser"));
    out.writeObject(myObject);
} finally {
    if (out != null) {
        out.close();
    }
}

This is verbose and error-prone.

The Modern Way: Try-With-Resources

Both ObjectOutputStream and ObjectInputStream implement AutoCloseable, so you can use try-with-resources. The stream automatically closes when the block ends—even if an exception occurs:

try (ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("data.ser"))) {
    out.writeObject(myObject);
} // Stream closes automatically here

try (ObjectInputStream in = new ObjectInputStream(new FileInputStream("data.ser"))) {
    MyClass obj = (MyClass) in.readObject();
} // Stream closes automatically here

The stream closes in the correct order (innermost first), and you don't need explicit close() calls or finally blocks.

Key Takeaway: Always use try-with-resources when working with ObjectOutputStream and ObjectInputStream to guarantee proper cleanup and prevent resource leaks, even when exceptions occur.