javabeginner

Try-With-Resources and AutoCloseable

Manage resources safely with try-with-resources: files, connections, streams, and custom resources.

java
import java.io.*;
import java.sql.*;
import java.net.http.*;
import java.net.URI;

public class ResourceManagement {

    // 1. File I/O — auto-closed
    static void readFile(String path) throws IOException {
        try (var reader = new BufferedReader(new FileReader(path))) {
            reader.lines().forEach(System.out::println);
        } // reader.close() called automatically
    }

    // 2. Multiple resources
    static void copyFile(String src, String dst) throws IOException {
        try (
            var in = new BufferedInputStream(new FileInputStream(src));
            var out = new BufferedOutputStream(new FileOutputStream(dst))
        ) {
            in.transferTo(out);
        }
    }

    // 3. JDBC connection
    static void queryDb(String url) throws SQLException {
        try (
            Connection conn = DriverManager.getConnection(url);
            PreparedStatement stmt = conn.prepareStatement("SELECT * FROM users WHERE age > ?");
        ) {
            stmt.setInt(1, 18);
            try (ResultSet rs = stmt.executeQuery()) {
                while (rs.next()) {
                    System.out.println(rs.getString("name"));
                }
            }
        }
    }

    // 4. Custom AutoCloseable
    static class Timer implements AutoCloseable {
        private final String label;
        private final long start;

        Timer(String label) {
            this.label = label;
            this.start = System.nanoTime();
            System.out.println("START: " + label);
        }

        @Override
        public void close() {
            long ms = (System.nanoTime() - start) / 1_000_000;
            System.out.printf("END: %s (%d ms)%n", label, ms);
        }
    }

    public static void main(String[] args) throws Exception {
        try (var timer = new Timer("demo")) {
            Thread.sleep(100);
        } // prints: END: demo (100 ms)
    }
}

Use Cases

  • Safe resource management preventing leaks
  • JDBC connection lifecycle management
  • Performance timing with custom AutoCloseable

Tags

Related Snippets

Similar patterns you can reuse in the same workflow.