Write your own AutoCloseable class
40 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)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
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"); }}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, somainneeds nocatch. - Even if
runthrew an exception, the logout line would still print, because try-with-resources callsclose()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.
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
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()); } }}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
BadLabSeatadds 1 back on everyclose(), so closing it twice reports 4 free computers out of 3.LabSeatuses aclosedflag: the secondclose()returns at once, andrunafter closing throws a clearIllegalStateException.
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
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"); } }}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 errorWhat this code does
close()copies the broadthrows ExceptionfromAutoCloseable, so the hiddenclose()call at the end of thetrymust be handled.- Nothing in this
close()can fail. Removethrows Exceptionand 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
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); } }}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 eachtryblock 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
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)); }}files inside: 2 temp folder deleted folder still exists: false
What this code does
TempFoldercreates a folder in the constructor and deletes the files it made, then the folder, inclose().Files.listreturns a stream that must be closed, so it gets its owntry.- After the
try,Files.exists(used)isfalse: nothing is left on the disk, even if the body had thrown.
Example 6 · An undo action: release an unpaid seat
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); }}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 andclose()keeps the seat. Rohit's payment fails, soclose()gives his seat back before thecatchruns. - 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