The Problem of Resource Leaks
What you'll learn: You'll understand how failing to close resources causes your application to slowly degrade and eventually fail.
What Is a Resource Leak?
A resource leak happens when your program opens a resource (like a file, database connection, or network socket) but never closes it. Think of it like leaving faucets running in your house—eventually, you'll run out of water pressure or flood the place.
When you open a resource in Java, the operating system allocates system handles, memory, and other limited resources. If you don't explicitly close these resources, they remain allocated even after your code stops using them. The garbage collector won't clean them up automatically because the system-level handles exist outside Java's memory management.
The Consequences
Unclosed resources accumulate over time, causing:
- Handle exhaustion: Operating systems limit the number of open files or sockets per process. Hit that limit, and new operations fail.
- Memory leaks: Buffers and internal data structures tied to resources consume heap space indefinitely.
- Connection pool depletion: Database connections remain "borrowed" but idle, preventing other parts of your application from accessing the database.
- Degraded performance: The application slows down as resources pile up.
- Eventual failure: Your application crashes or becomes unresponsive.
The Invisible Danger
Resource leaks are insidious because they don't always cause immediate errors. Your program might run fine during testing but fail in production after hours or days of operation. Each leaked resource is a small wound that eventually becomes fatal.
Key Takeaway: Resource leaks occur when resources aren't properly closed, consuming system handles, memory, and connections until your application degrades or fails. Always ensure resources are closed, which is why try-with-resources is essential.