Several resources and their close order
35 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)One try-with-resources can hold several resources, separated by semicolons. Java opens them from left to right and closes them in the opposite order, and it closes every resource that did open, even when a later one fails.
Declaring several resources with semicolons
To declare several resources, separate the declarations with a semicolon inside the same brackets: try (BufferedReader in = ...; BufferedWriter out = ...) { ... }. A semicolon after the last one is allowed but not needed.
Example 1 · Two resources in one try
class Part implements AutoCloseable { private final String name;
Part(String name) { if (name.startsWith("faulty")) { throw new IllegalStateException(name + " did not switch on"); } this.name = name; System.out.println("open " + name); }
@Override public void close() { System.out.println("close " + name); }}
public class TwoResourcesDemo { public static void main(String[] args) { try (Part speaker = new Part("speaker"); Part mic = new Part("mic")) { System.out.println("body: announcing the fest results"); } System.out.println("after the try"); }}open speaker open mic body: announcing the fest results close mic close speaker after the try
What this code does
- The speaker opens first and the mic second; the semicolon separates the two declarations.
- After the body, the mic closes first and the speaker last: reverse order, with no
finallywritten.
Example 2 · Read one file and write another
import java.io.BufferedReader;import java.io.BufferedWriter;import java.io.IOException;import java.nio.file.Files;import java.nio.file.Path;
public class CopyTopperDemo { static void copyTopper(Path from, Path to) throws IOException { try (BufferedReader in = Files.newBufferedReader(from); BufferedWriter out = Files.newBufferedWriter(to)) { out.write("Topper: " + in.readLine()); out.newLine(); } }
public static void main(String[] args) throws IOException { Path folder = Files.createTempDirectory("results"); Path marks = folder.resolve("marks.txt"); Path report = folder.resolve("report.txt"); Files.writeString(marks, "Meera,96\nKabir,88\n");
copyTopper(marks, report); System.out.println(report.getFileName() + ": " + Files.readString(report).trim());
Files.delete(marks); Files.delete(report); Files.delete(folder); }}report.txt: Topper: Meera,96
What this code does
- This is the copy from the old-style lesson, now in four lines: one
trywith a reader and a writer. - When the block ends,
outis closed first (its text is written to the disk), thenin.
This one try replaces the nested try-finally blocks of old code. Each resource can use the ones declared before it, for example a writer that is built from an earlier reader or stream.
Closing in reverse order
Java closes resources in reverse order of declaration: the last one declared is closed first. This matches how resources depend on each other.
Example 3 · Three resources close last to first
class Part implements AutoCloseable { private final String name;
Part(String name) { if (name.startsWith("faulty")) { throw new IllegalStateException(name + " did not switch on"); } this.name = name; System.out.println("open " + name); }
@Override public void close() { System.out.println("close " + name); }}
public class ReverseOrderDemo { public static void main(String[] args) { try (Part sound = new Part("sound system"); Part mic = new Part("mic on the sound system"); Part recording = new Part("recording from the mic")) { System.out.println("body: recording the college band"); throw new IllegalStateException("power cut"); } catch (IllegalStateException e) { System.out.println("catch: " + e.getMessage()); } }}open sound system open mic on the sound system open recording from the mic body: recording the college band close recording from the mic close mic on the sound system close sound system catch: power cut
What this code does
- The body throws a power-cut error, yet all three parts are closed, from the recording back to the sound system.
- The
catchruns only after the lastclose, so it never sees an open resource.
A recording depends on the mic, and the mic depends on the sound system, so the recording must stop before the mic is switched off.
The order stays the same when the body throws. All resources are closed, last to first, and only then does the catch block run.
Predict the output
Close order
Read the code and pick what it prints.
Round 1 of 2
What does this program print?
What happens when the second resource fails to open
Resources open one at a time. If the second open fails, the first one is already open, so Java closes it. The second was never created, so there is nothing to close. Any resource after it is never opened at all.
Example 4 · The second resource fails to open
class Part implements AutoCloseable { private final String name;
Part(String name) { if (name.startsWith("faulty")) { throw new IllegalStateException(name + " did not switch on"); } this.name = name; System.out.println("open " + name); }
@Override public void close() { System.out.println("close " + name); }}
public class SecondFailsDemo { public static void main(String[] args) { try (Part projector = new Part("projector"); Part laptop = new Part("faulty laptop"); Part clicker = new Part("clicker")) { System.out.println("body: showing the slides"); } catch (IllegalStateException e) { System.out.println("catch: " + e.getMessage()); } }}open projector close projector catch: faulty laptop did not switch on
What this code does
- The projector opens; the laptop constructor throws. Java closes the projector at once.
- The clicker is never created and the body never runs. The
catchgets the laptop's error.
The body does not run. The exception from the failed open goes to the catch block, or to the caller if there is none. You get this safety for free; in old code it took one more try-finally level per resource.
Wrapped streams: which object to declare
A wrapped stream is one object built around another, like new BufferedReader(new FileReader(file)). The outer object adds a feature (a buffer); the inner one holds the file handle. Closing the outer object also closes the inner one.
Example 5 · A wrapper whose constructor throws
import java.io.BufferedReader;import java.io.IOException;import java.io.StringReader;
class TrackedReader extends StringReader { TrackedReader(String text) { super(text); System.out.println(" open inner reader"); }
@Override public void close() { super.close(); System.out.println(" close inner reader"); }}
public class WrappedLeakDemo { public static void main(String[] args) { int bufferSize = 0; // a bad value from a settings file
System.out.println("One declaration:"); try (BufferedReader br = new BufferedReader(new TrackedReader("Asha,87"), bufferSize)) { System.out.println(" " + br.readLine()); } catch (IllegalArgumentException | IOException e) { System.out.println(" error: " + e.getMessage()); }
System.out.println("Two declarations:"); try (TrackedReader in = new TrackedReader("Asha,87"); BufferedReader br = new BufferedReader(in, bufferSize)) { System.out.println(" " + br.readLine()); } catch (IllegalArgumentException | IOException e) { System.out.println(" error: " + e.getMessage()); } }}One declaration: open inner reader error: Buffer size <= 0 Two declarations: open inner reader close inner reader error: Buffer size <= 0
What this code does
new BufferedReader(reader, 0)throwsIllegalArgumentException: Buffer size <= 0. With one declaration, the inner reader was created but nothing holds it, so it is never closed.- With two declarations,
inis a resource of its own. The wrapper fails, and Java closesinbecause it opened successfully.
Example 6 · Declare the outer writer too
import java.io.BufferedWriter;import java.io.IOException;import java.io.StringWriter;
class TrackedWriter extends StringWriter { @Override public void close() throws IOException { super.close(); System.out.println(" close inner writer"); }}
public class DeclareOuterDemo { public static void main(String[] args) throws IOException { System.out.println("Only the inner writer declared:"); TrackedWriter sheet1 = new TrackedWriter(); try (sheet1) { BufferedWriter out = new BufferedWriter(sheet1); out.write("Asha 87"); } System.out.println(" saved: '" + sheet1 + "'");
System.out.println("Inner and outer declared:"); TrackedWriter sheet2 = new TrackedWriter(); try (sheet2; BufferedWriter out = new BufferedWriter(sheet2)) { out.write("Asha 87"); } System.out.println(" saved: '" + sheet2 + "'"); }}Only the inner writer declared: close inner writer saved: '' Inner and outer declared: close inner writer close inner writer saved: 'Asha 87'
What this code does
- When only the inner writer is closed, the text is still sitting in the
BufferedWriter's buffer and never reachessheet1. The saved text is empty. - With both declared, closing
outflushes the buffer and closessheet2; then Java closessheet2again. The second close is harmless, which is why declaring both is safe.
- Declare the inner object first, then the wrapper:
try (Reader in = ...; BufferedReader br = new BufferedReader(in)) { }. - Always declare the outermost wrapper too: closing it flushes its buffer.
Files.newBufferedReader(path)andFiles.newBufferedWriter(path)give one object, so there is nothing to wrap.
The trap: if only the outer object is declared and its constructor throws, the inner object was already created, but no variable holds it, so nothing closes it. The safe habit is to declare each object as its own resource. Closing the inner one twice is harmless, because Closeable says a second close() does nothing.
Next step
Check your understanding
12 quick questions