try-with-resources: Automatic Closing in Reverse Order
javaJavabeginnerinterview-prepjava
Two AutoCloseable resources declared in a try header are closed automatically, last opened first, and the code after the block still runs.
public class TryWithResourcesDemo {
public static void main(String[] args) {
try (Connection connection = new Connection("database"); Statement statement = new Statement("query")) {
System.out.println("working");
} // statement closes first, then connection
System.out.println("done");
}
}
class Connection implements AutoCloseable {
private final String name;
Connection(String name) { this.name = name; System.out.println("open " + name); }
@Override public void close() { System.out.println("close " + name); }
}
class Statement implements AutoCloseable {
private final String name;
Statement(String name) { this.name = name; System.out.println("open " + name); }
@Override public void close() { System.out.println("close " + name); }
}