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

java
@Component
@Converter
public class EncryptedStringConverter implements AttributeConverter<String, String> {
 

Transparent column encryption in Spring & JPA

encryption aes-gcm jpa-converter
Advanced 10 steps
java
package com.acme.billing.config;
 
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.ConfigurationProperties;

Feature-flagged beans with Spring @ConditionalOnProperty

feature-flags conditional-beans strategy-pattern
Intermediate 5 steps
java
public static Map<String, String> parseCookieHeader(String header) {
    Map<String, String> cookies = new LinkedHashMap<>();
    if (header == null || header.isBlank()) {
        return cookies;

Parsing an HTTP Cookie header in Java

string-parsing http url-decoding
Intermediate 6 steps
java
public class TimedSocketReader {
 
    private static final int READ_TIMEOUT_MS = 5_000;
    private static final int CONNECT_TIMEOUT_MS = 3_000;

Reading a socket with connect and read timeouts

sockets timeouts io
Intermediate 8 steps
javascript
import { useEffect, useRef, useState } from 'react';
 
export function useDelayedFlag(active, delay = 300) {
  const [visible, setVisible] = useState(false);

Delaying a loading spinner with a React hook

custom-hooks debouncing cleanup
Intermediate 8 steps
javascript
const SWIPE_THRESHOLD = 80;
const MAX_TRANSLATE = 120;
 
export function attachSwipeToDismiss(element, onDismiss) {

Building a swipe-to-dismiss gesture in JS

touch-events gesture-detection dom-manipulation
Intermediate 10 steps

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