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 class ThumbnailProcessor { private static final int MAX_CONCURRENCY = 4;
Bounded parallel thumbnail rendering in Java
concurrency
thread-pool
futures
Intermediate
7 steps
java
public class SortedListMerger { public static int[] merge(int[] a, int[] b) { int[] result = new int[a.length + b.length];
Merging two sorted arrays in Java
two-pointers
merging
arrays
Beginner
6 steps
java
import java.util.ArrayDeque; import java.util.Deque; public final class RollingAverage {
A rolling average over a sliding window
sliding-window
running-sum
deque
Intermediate
7 steps
java
@Target({ElementType.FIELD, ElementType.PARAMETER}) @Retention(RetentionPolicy.RUNTIME) @Constraint(validatedBy = StrongPasswordValidator.class) @Documented
Building a custom @StrongPassword validator in Spring
bean-validation
annotations
regex
Intermediate
7 steps
java
@Component public class JwtAuthenticationFilter extends OncePerRequestFilter { private final JwtTokenProvider tokenProvider;
How a JWT auth filter works in Spring
authentication
jwt
servlet-filter
Intermediate
8 steps
java
@Entity @Table(name = "accounts") public class Account {
Optimistic locking with @Version in Spring
optimistic-locking
jpa
concurrency
Advanced
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.