library
beginnertry-with-resources & AutoCloseable
Automatically close resources (streams, connections, locks) and avoid resource leaks using the try-with-resources statement.
try-with-resources (Java 7) ensures that resources implementing AutoCloseable or Closeable are automatically closed when the try block exits — whether normally or via exception.
try-with-resources = a hotel checkout guarantee. You check into rooms (open resources) and the hotel guarantees checkout (close) even if you leave in a hurry (exception). If checkout itself fails, that problem is noted but doesn't prevent you from leaving.
Key Concepts
1
Syntax: declare resources in the try parentheses. They're closed in reverse declaration order. If both the try block and close() throw, the close exception is suppressed (accessible via getSuppressed()).
2
AutoCloseable vs Closeable:
- AutoCloseable: close() throws Exception. Broader, for any resource.
- Closeable: close() throws IOException. Extends AutoCloseable. For I/O resources.
3
Effectively-final variables (Java 9): resources declared outside the try can be used if they're effectively final.
4
Best practices:
- Always use try-with-resources for: streams, connections, readers/writers, channels, locks (if implementing AutoCloseable)
- Don't manually close in finally blocks — try-with-resources handles edge cases better
- If a resource shouldn't be closed (shared connection pool), don't put it in try-with-resources
5
Custom resources: implement AutoCloseable with a close() method. Useful for temporary files, lock wrappers, transaction contexts, metric timers.