Replace finally-close code with try-with-resources
40 min · Advanced
Need help? Ask a tutor on WhatsApp (opens in a new tab)Most old close code can become try-with-resources in a few safe steps. A few clean-up jobs, such as unlocking a lock or resetting a flag, still belong in finally, and a resource returned from a method must have one clear owner who closes it.
Refactoring old close code step by step
Refactoring means changing how code is written without changing what it does. Turning try-finally close code into try-with-resources is one of the safest refactors in Java, as long as you do it in small steps and keep each catch that was there.
- Find each resource and the
finallyblock that closes it. - Move the open into the brackets after
try, one declaration per resource, in the same order. - Delete the
close()calls, the null checks and the= nulldeclarations. - Merge nested
tryblocks into one; keep anycatchblocks after it. - If the variable was used after the
try, keep what you need in a variable declared before it.
Example 1 · The same copy, before and after the refactor
import java.io.IOException;
class PretendFile implements AutoCloseable { private final String name;
PretendFile(String name) throws IOException { if (name.startsWith("missing")) { throw new IOException("cannot open " + name); } this.name = name; System.out.println(" open " + name); }
String readLine() throws IOException { if (name.contains("broken")) { throw new IOException("read error in " + name); } return "data from " + name; }
void write(String text) { System.out.println(" write '" + text + "' to " + name); }
@Override public void close() throws IOException { if (name.startsWith("usb")) { throw new IOException("close failed: " + name); } System.out.println(" close " + name); }}
public class RefactorDemo { // Before: nested try-finally static void copyOld(String from, String to) throws IOException { PretendFile in = new PretendFile(from); try { PretendFile out = new PretendFile(to); try { out.write(in.readLine()); } finally { out.close(); } } finally { in.close(); } }
// After: same behaviour, one try static void copyNew(String from, String to) throws IOException { try (PretendFile in = new PretendFile(from); PretendFile out = new PretendFile(to)) { out.write(in.readLine()); } }
static void test(String label, String from, String to) { System.out.println(label + " " + from + " -> " + to); try { if (label.equals("old")) { copyOld(from, to); } else { copyNew(from, to); } } catch (IOException e) { System.out.println(" error: " + e.getMessage() + " (suppressed: " + e.getSuppressed().length + ")"); } }
public static void main(String[] args) { test("old", "marks.txt", "report.txt"); test("new", "marks.txt", "report.txt"); test("old", "usb-broken.txt", "report.txt"); test("new", "usb-broken.txt", "report.txt"); }}old marks.txt -> report.txt open marks.txt open report.txt write 'data from marks.txt' to report.txt close report.txt close marks.txt new marks.txt -> report.txt open marks.txt open report.txt write 'data from marks.txt' to report.txt close report.txt close marks.txt old usb-broken.txt -> report.txt open usb-broken.txt open report.txt close report.txt error: close failed: usb-broken.txt (suppressed: 0) new usb-broken.txt -> report.txt open usb-broken.txt open report.txt close report.txt error: read error in usb-broken.txt (suppressed: 1)
What this code does
- For a normal copy, the old and new methods print exactly the same lines: open, open, write, close, close.
- For
usb-broken.txt, the read fails and then the close fails. The old method reports the close failure and loses the read error; the new one reports the read error and keeps the close failure as suppressed.
The new code behaves the same on the normal path and when an open fails. It differs in one way, and only for the better: when the body and a close() both throw, the caller now gets the body's exception, with the close failure suppressed.
When finally is still the right tool: unlock, reset state
finally is still the right tool when the clean-up is not a close(). A ReentrantLock is released with unlock(), and it does not implement AutoCloseable. The standard pattern is lock.lock(); try { ... } finally { lock.unlock(); }, with lock() before the try.
Example 2 · Unlock a lock in finally
import java.util.concurrent.locks.ReentrantLock;
public class LockFinallyDemo { static final ReentrantLock seatLock = new ReentrantLock(); static int seatsLeft = 1;
static void book(String name) { seatLock.lock(); // lock before try try { if (seatsLeft == 0) { throw new IllegalStateException("no seat left for " + name); } seatsLeft--; System.out.println("Booked the last seat for " + name); } finally { seatLock.unlock(); // always released } }
public static void main(String[] args) { book("Asha"); try { book("Ravi"); } catch (IllegalStateException e) { System.out.println("Error: " + e.getMessage()); } System.out.println("Lock still held: " + seatLock.isLocked()); }}Booked the last seat for Asha Error: no seat left for Ravi Lock still held: false
What this code does
- Ravi's booking throws inside the
try, yetfinallystill callsunlock(). Otherwise every later booking would wait for the lock forever. lock()sits before thetry, sofinallyonly runs when the lock was really taken.
Example 3 · Reset a flag in finally
public class ResetStateDemo { static boolean maintenance = false;
static void runBackup(boolean diskFull) { maintenance = true; System.out.println("maintenance on: portal closed for students"); try { if (diskFull) { throw new IllegalStateException("backup disk full"); } System.out.println("backup of results done"); } finally { maintenance = false; // reset, even on failure System.out.println("maintenance off"); } }
public static void main(String[] args) { runBackup(false); try { runBackup(true); } catch (IllegalStateException e) { System.out.println("Error: " + e.getMessage()); } System.out.println("Students can log in: " + !maintenance); }}maintenance on: portal closed for students backup of results done maintenance off maintenance on: portal closed for students maintenance off Error: backup disk full Students can log in: true
What this code does
- The second backup fails, but
finallyturns maintenance off before the error reachesmain. - Without the
finally, a full disk would leave the portal closed for every student until someone restarted the program.
Example 4 · A lock adapter for try-with-resources
import java.util.concurrent.locks.Lock;import java.util.concurrent.locks.ReentrantLock;
interface Held extends AutoCloseable { @Override void close(); // no checked exception}
public class LockAdapterDemo { static final ReentrantLock lock = new ReentrantLock();
static Held hold(Lock l) { l.lock(); return l::unlock; // close() will call unlock() }
public static void main(String[] args) { try (Held h = hold(lock)) { System.out.println("inside: locked = " + lock.isLocked()); } System.out.println("after: locked = " + lock.isLocked());
try (Held h = hold(lock)) { throw new IllegalStateException("hostel allotment failed"); } catch (IllegalStateException e) { System.out.println("error: " + e.getMessage() + ", locked = " + lock.isLocked()); } }}inside: locked = true after: locked = false error: hostel allotment failed, locked = false
What this code does
Heldis anAutoCloseablewhoseclose()throws nothing. It has one abstract method, so the method referencel::unlockcan be aHeld.hold(lock)locks and returns aHeld; try-with-resources then unlocks it on every path, including the failure.
The same goes for resetting state: a flag turned on for a task, a counter of active users, a setting changed for one job. Put the reset in finally so a failure cannot leave the program stuck in the wrong state. If you use the same pair in many places, you can wrap it in a small AutoCloseable adapter, as Example 4 shows.
lock() before the try, not inside it. If lock() itself failed inside the try, finally would call unlock() on a lock you never got and throw IllegalMonitorStateException.Resources returned from methods: who closes them
Ownership decides who closes a resource: the code that opens it closes it, unless it hands it to someone else. A method that returns an open resource gives ownership to its caller.
Example 5 · Bug and fix: returning a closed reader
import java.io.BufferedReader;import java.io.IOException;import java.nio.file.Files;import java.nio.file.Path;
public class ReturnResourceDemo { static BufferedReader openBad(Path file) throws IOException { try (BufferedReader r = Files.newBufferedReader(file)) { return r; // closed on the way out } }
static BufferedReader openGood(Path file) throws IOException { return Files.newBufferedReader(file); // the caller now owns it }
public static void main(String[] args) throws IOException { Path file = Files.createTempFile("toppers", ".txt"); Files.writeString(file, "Meera,96\n");
try { BufferedReader r = openBad(file); System.out.println("bad: " + r.readLine()); } catch (IOException e) { System.out.println("bad: " + e.getMessage()); }
try (BufferedReader r = openGood(file)) { System.out.println("good: " + r.readLine()); }
Files.delete(file); }}bad: Stream closed good: Meera,96
What this code does
openBadreturnsrfrom inside its own try-with-resources, soris closed before the caller gets it. The firstreadLine()fails withStream closed.openGoodreturns the reader open and hands over ownership. The caller closes it with try-with-resources.
Example 6 · Bug and fix: closing a borrowed reader
import java.io.BufferedReader;import java.io.IOException;import java.io.StringReader;
public class BorrowedResourceDemo { static String header(BufferedReader r) throws IOException { return r.readLine(); // borrows r, does not close it }
static String headerAndClose(BufferedReader r) throws IOException { try (r) { // closes something it does not own return r.readLine(); } }
public static void main(String[] args) throws IOException { String csv = "name,marks\nAsha,87\n";
try (BufferedReader r = new BufferedReader(new StringReader(csv))) { System.out.println("header: " + header(r)); System.out.println("row: " + r.readLine()); }
try (BufferedReader r = new BufferedReader(new StringReader(csv))) { System.out.println("header: " + headerAndClose(r)); System.out.println("row: " + r.readLine()); } catch (IOException e) { System.out.println("error: " + e.getMessage()); } }}header: name,marks row: Asha,87 header: name,marks error: Stream closed
What this code does
headerreads the first line and leavesropen, somaincan go on to read the data row.headerAndClosecloses a reader it only borrowed. Back inmain, the nextreadLine()fails withStream closed.
So the method must not close it, and the caller must use try-with-resources on the result. The opposite case: a method that receives a resource as a parameter only borrows it. It must not close it, because the caller may still need it. A common bug is a helper method that returns a reader from inside its own try-with-resources: the caller gets an object that is already closed, and the first read fails with IOException: Stream closed.
- Opens and uses it: close it with try-with-resources.
- Opens and returns it: do not close it; the caller owns it now.
- Receives it as a parameter: do not close it; the caller still owns it.
Interview: finally versus try-with-resources
In interviews, the honest answer is that both are still used, for different jobs. try-with-resources is for objects with a close() method; finally is for any other clean-up that must always run.
- try-with-resources: less code, closes in reverse order, no null checks, keeps the body's exception and suppresses close failures.
finally: forunlock(), resetting flags and other clean-up that is not anAutoCloseable.finallycan hide the real error if its own code throws; keep it short and safe.- Both can be used together: a try-with-resources may have its own
catchandfinally.
Next step
Check your understanding
12 quick questions