try-with-resources
try-with-resources opens one or more AutoCloseable values in a try (...) header and closes them when the block ends, even if the block throws.
Detailed Explanation
A file handle, a socket, or a JDBC statement is a resource the operating system owns. If you forget close(), you leak them. The old pattern was try { ... } finally { stream.close(); }. That is easy to get wrong: close itself can throw, and a thrown close can hide the exception from the body.
try-with-resources (Java 7) is the language fix. You declare the resource in the try header. The compiler emits close() in a generated finally. If the body throws and close also throws, the body's exception is the one callers see. The close exception is attached as a suppressed exception, visible with getSuppressed(). That is why logs suddenly show two stack traces on one throw.
The resource type must implement AutoCloseable (or Closeable, which extends it). close may throw Exception. Closeable.close is narrower (IOException). You can declare several resources, separated by ;. They close in reverse order of declaration: the last opened is the first closed, which matches nested dependencies (a Statement before its Connection would be wrong if you opened the connection first and the statement second — close statement, then connection).
From Java 9 you may use an effectively final variable in the header (try (stream)). The variable still must implement AutoCloseable. Do not close the resource yourself in the body unless the API requires an early close; double-close is supposed to be safe, but not every implementation is.
You reach for try-with-resources whenever you construct an AutoCloseable for the duration of a block. You keep a manual close only when the lifetime is longer than the method (a connection owned by a pool, a server socket owned by a server). Pools usually want close() to mean "return to the pool", and wrapping that in try-with-resources is still correct.
The cost of forgetting it is a leak that shows up under load. The cost of using it on a shared resource is closing something a caller still needs. Ownership should be obvious: the method that created the resource closes it, or it returns the resource and documents that the caller owns it.
Code Examples
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
public class ReadAll {
static String read(Path path) throws IOException {
// BufferedReader is closed even if readLine throws.
try (var reader = Files.newBufferedReader(path, StandardCharsets.UTF_8)) {
return reader.readLine();
}
}
}import java.util.ArrayList;
import java.util.List;
public class DemoClose implements AutoCloseable {
static final List<String> log = new ArrayList<>();
private final String name;
DemoClose(String name) {
this.name = name;
log.add("open " + name);
}
@Override
public void close() {
log.add("close " + name);
}
public static void main(String[] args) {
try (DemoClose a = new DemoClose("a"); DemoClose b = new DemoClose("b")) {
log.add("body");
}
System.out.println(log); // prints: [open a, open b, body, close b, close a]
}
}Common Gotchas
Closing order is reverse of declaration
open a connection first and a statement second so the statement closes first.
Suppressed exceptions hide on `close`
always log `e.getSuppressed()` when diagnosing a failed try-with-resources.
Returning a resource from inside the `try` closes it before the caller receives it
do not wrap a resource you intend to hand out.
The type must implement `AutoCloseable`
a random object in the header does not compile.