Why Closing Streams Matters: Resource Leaks Explained
You'll learn why forgetting to close streams can cripple your application by exhausting operating system resources.
The Hidden Cost of Open Streams
When you open a FileInputStream or FileOutputStream, Java doesn't work alone—it asks the operating system for a file descriptor, a low-level handle that grants access to the physical file. Think of file descriptors like library cards: the library (your OS) only has a limited number to hand out. If patrons never return their cards, eventually no one else can check out books.
Every stream you open consumes one of these precious file descriptors. Your operating system has strict limits—typically a few thousand per process. If your program opens streams without closing them, you'll eventually hit this ceiling and get a dreaded error like "Too many open files."
What Happens When You Don't Close
// DANGEROUS: Resource leak!
FileInputStream fis = new FileInputStream("data.bin");
fis.read(); // Use the stream
// ...forgot to call fis.close()
This stream stays open indefinitely, hogging its file descriptor. The file remains locked, other programs may be blocked from accessing it, and your OS resource pool shrinks. In a loop processing hundreds of files, you'll exhaust resources within seconds.
Real-World Impact
- File locks: On some systems, unclosed output streams prevent other processes from reading the file
- Memory pressure: Buffers remain allocated even when you're done
- System-wide failure: Not just your app—other programs may fail to open files
Key Takeaway: Always close streams to release file descriptors back to the OS; use try-with-resources to guarantee cleanup even when exceptions occur.