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
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Any class implementing AutoCloseable can participate in try-with-resources, not just built-in IO types.
- 2close() is guaranteed to run when the try block exits, whether it returns normally or throws.
- 3Multiple resources in one try header are closed in reverse order of declaration, mirroring safe teardown.
Related explainers
java
public interface GitHubClient { @GetExchange("/users/{username}") GitHubUser getUser(@PathVariable String username);
Declarative HTTP clients in Spring
http-client
declarative-api
proxy
Intermediate
8 steps
java
import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map;
Building a trie for autocomplete in Java
trie
prefix-tree
recursion
Intermediate
8 steps
java
@RestController @RequestMapping("/api/products") public class ProductSearchController {
Binding collection query params in Spring
rest-api
query-parameters
dependency-injection
Intermediate
6 steps
java
import java.util.ArrayDeque; import java.util.Deque; import java.util.Map;
Evaluating math expressions with two stacks
stacks
parsing
operator-precedence
Intermediate
9 steps
java
@Entity @Table(name = "orders") @SQLDelete(sql = "UPDATE orders SET deleted = true, deleted_at = now() WHERE id = ?") @Where(clause = "deleted = false")
Soft deletes with Hibernate in Spring
soft-delete
jpa
hibernate
Intermediate
9 steps
javascript
import { useState, useEffect, useCallback } from 'react'; function getColumnCount(width) { if (width < 640) return 1;
A responsive column hook in React
custom-hooks
debouncing
responsive-design
Intermediate
7 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/java-try-with-resources-and-autocloseable-explained-java-3c19/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.