java 41 lines · 6 steps

Java try-with-resources and AutoCloseable

How implementing AutoCloseable lets try-with-resources clean up your objects automatically, even when code throws.

Explained by highlit
1import java.io.BufferedReader;
2import java.io.FileReader;
3import java.io.IOException;
4 
5public class ResourceManagement {
6 
7 // A custom AutoCloseable resource whose close() is invoked automatically.
8 static class DatabaseConnection implements AutoCloseable {
9 private final String name;
10 
11 DatabaseConnection(String name) {
12 this.name = name;
13 System.out.println("Opening connection: " + name);
14 }
15 
16 void query(String sql) {
17 System.out.println("[" + name + "] executing: " + sql);
18 }
19 
20 @Override
21 public void close() {
22 System.out.println("Closing connection: " + name);
23 }
24 }
25 
26 // Single resource: close() runs whether the block completes or throws.
27 String readFirstLine(String path) throws IOException {
28 try (BufferedReader reader = new BufferedReader(new FileReader(path))) {
29 return reader.readLine();
30 }
31 }
32 
33 // Multiple resources are closed in reverse order of declaration.
34 void runTransaction() {
35 try (DatabaseConnection primary = new DatabaseConnection("primary");
36 DatabaseConnection replica = new DatabaseConnection("replica")) {
37 primary.query("INSERT INTO orders VALUES (1)");
38 replica.query("SELECT * FROM orders");
39 }
40 }
41}
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1Any class implementing AutoCloseable can participate in try-with-resources, not just built-in IO types.
  2. 2close() is guaranteed to run when the try block exits, whether it returns normally or throws.
  3. 3Multiple resources in one try header are closed in reverse order of declaration, mirroring safe teardown.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Java try-with-resources and AutoCloseable — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code