Skip to lesson

Write your own AutoCloseable class

Files are not the only things that need closing: a timer, a temporary folder or a database transaction must also be finished, even when an error happens. How do you give your own class that safety?

Implementing close

AutoCloseable is the interface with a single close method; any class that implements it can be used in try-with-resources.

To make a custom resource, write class X implements AutoCloseable and give it a public void close() method with your clean-up code. The constructor (or a factory method) does the "open" part, and close() does the "give back" part.

Example 1 · A lab session that logs out by itself

LabSessionDemo.javaJava
class LabSession implements AutoCloseable {    private final String student;
    LabSession(String student) {        this.student = student;        System.out.println(student + " logged in to lab PC 12");    }
    void run(String program) {        System.out.println("  running " + program);    }
    @Override    public void close() {        System.out.println(student + " logged out");    }}
public class LabSessionDemo {    public static void main(String[] args) {        try (LabSession s = new LabSession("Divya")) {            s.run("BubbleSort.java");            s.run("Fibonacci.java");        }        System.out.println("PC 12 is free again");    }}
Output
Divya logged in to lab PC 12
  running BubbleSort.java
  running Fibonacci.java
Divya logged out
PC 12 is free again

What this code does

  • The constructor logs in and close() logs out. close() declares no exception, so main needs no catch.
  • Even if run threw an exception, the logout line would still print, because try-with-resources calls close() on every path.

close() must be public, because interface methods are public. Mark it with @Override so the compiler checks that the name and parameters are right.

Keep close() short and focused on releasing. Avoid work in it that is likely to fail.

Making close safe to call twice

A close() method is idempotent when calling it a second time does nothing. This matters because the same object can be closed twice: by hand and then by try-with-resources, or by a wrapper and then directly.

Example 2 · Bug and fix: closing twice

SafeCloseDemo.javaJava
class BadLabSeat implements AutoCloseable {    static int free = 3;
    BadLabSeat() {        free--;    }
    @Override    public void close() {        free++;                              // runs again on every call    }}
class LabSeat implements AutoCloseable {    static int free = 3;    private final String student;    private boolean closed = false;
    LabSeat(String student) {        this.student = student;        free--;    }
    void run(String program) {        if (closed) {            throw new IllegalStateException("session of " + student + " is closed");        }        System.out.println("  " + student + " runs " + program);    }
    @Override    public void close() {        if (closed) {            return;        }        closed = true;        free++;    }}
public class SafeCloseDemo {    public static void main(String[] args) {        try (BadLabSeat seat = new BadLabSeat()) {            seat.close();                    // closed early by hand        }                                    // and again by try-with-resources        System.out.println("Bad seat: free computers = " + BadLabSeat.free + " of 3");
        LabSeat kept = null;        try (LabSeat seat = new LabSeat("Arjun")) {            seat.run("Calculator.java");            seat.close();            kept = seat;        }        System.out.println("Safe seat: free computers = " + LabSeat.free + " of 3");
        try {            kept.run("Late.java");        } catch (IllegalStateException e) {            System.out.println("Error: " + e.getMessage());        }    }}
Output
Bad seat: free computers = 4 of 3
  Arjun runs Calculator.java
Safe seat: free computers = 3 of 3
Error: session of Arjun is closed

What this code does

  • BadLabSeat adds 1 back on every close(), so closing it twice reports 4 free computers out of 3.
  • LabSeat uses a closed flag: the second close() returns at once, and run after closing throws a clear IllegalStateException.

Closeable requires it; AutoCloseable only recommends it, but every good resource does it.

The usual pattern is a boolean closed field. close() returns at once when it is already true. Other methods can check the same flag and throw IllegalStateException when someone uses the object after closing it.

Declaring a narrower exception on close, or none

AutoCloseable.close() is declared throws Exception. When you override it, you may narrow that: throw a subclass such as IOException, or declare no checked exception at all. Java allows an overriding method to throw less than the method it overrides.

Example 3 · Error: close() declared throws Exception

BroadCloseDemo.javaJava
class FeeLedger implements AutoCloseable {    @Override    public void close() throws Exception {        System.out.println("ledger saved");    }}
public class BroadCloseDemo {    public static void main(String[] args) {        try (FeeLedger ledger = new FeeLedger()) {            System.out.println("adding fee entries");        }    }}
Sample compiler output
BroadCloseDemo.java:10: error: unreported exception Exception; must be caught or declared to be thrown
        try (FeeLedger ledger = new FeeLedger()) {
                       ^
  exception thrown from implicit call to close() on resource variable 'ledger'
1 error

What this code does

  • close() copies the broad throws Exception from AutoCloseable, so the hidden close() call at the end of the try must be handled.
  • Nothing in this close() can fail. Remove throws Exception and the program compiles and prints both lines.

This matters for the people who use your class. If your close() says throws Exception, every try-with-resources on it must catch Exception, even though nothing can really fail. The AutoCloseable documentation asks you to declare the most specific exception, or none when closing cannot fail.

Uses: timers, temporary folders, undo actions

AutoCloseable fits any "do something, then always do the opposite" pair, not only files. A timer starts in the constructor and prints the time in close(). A temporary folder is created in the constructor and deleted in close().

Example 4 · A stopwatch resource

StopWatchDemo.javaJava
import java.util.Arrays;import java.util.Random;
class StopWatch implements AutoCloseable {    private final String task;    private final long start;
    StopWatch(String task) {        this.task = task;        this.start = System.nanoTime();    }
    @Override    public void close() {        long ms = (System.nanoTime() - start) / 1_000_000;        System.out.println(task + " took " + ms + " ms");    }}
public class StopWatchDemo {    public static void main(String[] args) {        int[] marks = new Random(7).ints(2_000_000, 0, 101).toArray();
        try (StopWatch w = new StopWatch("Sorting 2 million marks")) {            Arrays.sort(marks);        }        try (StopWatch w = new StopWatch("Counting full marks")) {            long full = Arrays.stream(marks).filter(m -> m == 100).count();            System.out.println("Students with 100: " + full);        }    }}
Sample output
Sorting 2 million marks took 85 ms
Students with 100: 19808
Counting full marks took 12 ms

What this code does

  • The clock starts in the constructor and the time is printed in close(), so each try block measures exactly its own body.
  • Times differ on every computer and every run; the count of students with 100 is the same because the random numbers use a fixed seed (7).

Example 5 · A temporary folder that deletes itself

TempFolderDemo.javaJava
import java.io.IOException;import java.nio.file.Files;import java.nio.file.Path;import java.util.ArrayList;import java.util.List;
class TempFolder implements AutoCloseable {    private final Path dir;    private final List<Path> files = new ArrayList<>();
    TempFolder(String prefix) throws IOException {        dir = Files.createTempDirectory(prefix);    }
    Path dir() {        return dir;    }
    Path newFile(String name, String text) throws IOException {        Path p = dir.resolve(name);        Files.writeString(p, text);        files.add(p);        return p;    }
    @Override    public void close() throws IOException {        for (Path p : files) {            Files.deleteIfExists(p);        }        Files.deleteIfExists(dir);        System.out.println("temp folder deleted");    }}
public class TempFolderDemo {    public static void main(String[] args) throws IOException {        Path used;        try (TempFolder tmp = new TempFolder("result-run")) {            tmp.newFile("cse.csv", "Asha,87\n");            tmp.newFile("ece.csv", "Ravi,72\n");            used = tmp.dir();            try (var list = Files.list(used)) {                System.out.println("files inside: " + list.count());            }        }        System.out.println("folder still exists: " + Files.exists(used));    }}
Output
files inside: 2
temp folder deleted
folder still exists: false

What this code does

  • TempFolder creates a folder in the constructor and deletes the files it made, then the folder, in close(). Files.list returns a stream that must be closed, so it gets its own try.
  • After the try, Files.exists(used) is false: nothing is left on the disk, even if the body had thrown.

Example 6 · An undo action: release an unpaid seat

SeatHoldDemo.javaJava
class SeatHold implements AutoCloseable {    static int freeSeats = 2;    private final String passenger;    private boolean confirmed = false;
    SeatHold(String passenger) {        if (freeSeats == 0) {            throw new IllegalStateException("no seats left for " + passenger);        }        this.passenger = passenger;        freeSeats--;        System.out.println("  seat held for " + passenger + " (free: " + freeSeats + ")");    }
    void confirm() {        confirmed = true;        System.out.println("  ticket confirmed for " + passenger);    }
    @Override    public void close() {        if (!confirmed) {                    // the undo action            freeSeats++;            System.out.println("  hold released for " + passenger + " (free: " + freeSeats + ")");        }    }}
public class SeatHoldDemo {    static void book(String passenger, boolean paymentOk) {        System.out.println("Booking for " + passenger + ":");        try (SeatHold hold = new SeatHold(passenger)) {            if (!paymentOk) {                throw new IllegalStateException("UPI payment failed");            }            hold.confirm();        } catch (IllegalStateException e) {            System.out.println("  error: " + e.getMessage());        }    }
    public static void main(String[] args) {        book("Meena", true);        book("Rohit", false);        book("Imran", true);        System.out.println("Seats left: " + SeatHold.freeSeats);    }}
Output
Booking for Meena:
  seat held for Meena (free: 1)
  ticket confirmed for Meena
Booking for Rohit:
  seat held for Rohit (free: 0)
  hold released for Rohit (free: 1)
  error: UPI payment failed
Booking for Imran:
  seat held for Imran (free: 0)
  ticket confirmed for Imran
Seats left: 0

What this code does

  • Meena pays, confirm() runs and close() keeps the seat. Rohit's payment fails, so close() gives his seat back before the catch runs.
  • Because Rohit's hold was released, Imran still gets a seat. Without the undo, the train would show a seat that nobody paid for.

A seat hold is taken in the constructor and given back in close(), unless it was confirmed.

The last idea is an undo action: the clean-up runs only if the work did not finish. Mark success with a method such as confirm() or commit(); close() then knows whether to undo.

Next step

Check your understanding

12 quick questions