Try-With-Resources & AutoCloseable Interface
1Concept
Java 7 Try-With-Resources automates resource management. Any class implementing `java.lang.AutoCloseable` declared in the try-header is automatically closed in reverse declaration order upon exiting the block, even if exceptions occur. Suppressed exceptions are preserved via `e.getSuppressed()`.
2Architecture Diagram
try (Resource r1 = new Res(); Resource r2 = new Res()) {
// Work
} // Compiler guarantees r2.close() followed by r1.close() automatically!3Code Example
Core Java
public class TryWithResourcesDemo {
static class ManagedDatabaseConnection implements AutoCloseable {
private String dbName;
public ManagedDatabaseConnection(String dbName) {
this.dbName = dbName;
System.out.println("Connected to " + dbName);
}
public void query() {
System.out.println("Executing SELECT queries on " + dbName);
}
@Override
public void close() {
System.out.println("Connection to " + dbName + " closed safely.");
}
}
public static void main(String[] args) {
try (ManagedDatabaseConnection conn = new ManagedDatabaseConnection("ProductionCluster")) {
conn.query();
} // AutoCloseable triggers automatically here!
System.out.println("Resource closed without explicit finally block.");
}
}4Expected Output
Connected to ProductionCluster Executing SELECT queries on ProductionCluster Connection to ProductionCluster closed safely. Resource closed without explicit finally block.
5Key Takeaways
- ✓Always prefer Try-With-Resources over legacy try-finally for streams, sockets, and JDBC connections.
- ✓Multiple resources are closed in the exact REVERSE order of their declaration.
- ✓Exceptions thrown during `close()` are added as 'suppressed' exceptions to the primary exception.