Skip to lesson

Several resources and their close order

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

TwoResourcesDemo.javaJava
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");    }}
Output
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 finally written.

Example 2 · Read one file and write another

CopyTopperDemo.javaJava
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);    }}
Output
report.txt: Topper: Meera,96

What this code does

  • This is the copy from the old-style lesson, now in four lines: one try with a reader and a writer.
  • When the block ends, out is closed first (its text is written to the disk), then in.

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.

Put each resource on its own line, lined up under the first. Long brackets are hard to read on one line.

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.

Two resources in one try-with-resources open in the order written (speaker, then mic), the body runs, and they close in reverse order (mic, then speaker). The last resource opened is the first one closed.

Example 3 · Three resources close last to first

ReverseOrderDemo.javaJava
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());        }    }}
Output
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 catch runs only after the last close, 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?

public class CloseOrderDemo {
static class Res implements AutoCloseable {
private final String name;
Res(String name) {
this.name = name;
System.out.println("open " + name);
}
public void close() {
System.out.println("close " + name);
}
}
public static void main(String[] args) {
try (Res a = new Res("A"); Res b = new Res("B")) {
System.out.println("body");
}
}
}

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

SecondFailsDemo.javaJava
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());        }    }}
Output
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 catch gets 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

WrappedLeakDemo.javaJava
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());        }    }}
Output
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) throws IllegalArgumentException: Buffer size <= 0. With one declaration, the inner reader was created but nothing holds it, so it is never closed.
  • With two declarations, in is a resource of its own. The wrapper fails, and Java closes in because it opened successfully.

Example 6 · Declare the outer writer too

DeclareOuterDemo.javaJava
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 + "'");    }}
Output
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 reaches sheet1. The saved text is empty.
  • With both declared, closing out flushes the buffer and closes sheet2; then Java closes sheet2 again. 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) and Files.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