Sub topic 14
Managing Multiple Resources
A resource is an object that must be closed when you finish with it, such as a file or a network connection. Many programs need more than one at a time. A copy program, for example, reads from one file and writes to another. try-with-resources can manage several resources in a single statement, and it closes all of them for you.
Declaring More Than One Resource
To declare several resources, list them inside the parentheses and put a semicolon between them. Each one must implement AutoCloseable. AutoCloseable is an interface with a single close() method.
The class below prints a message when it opens and when it closes, so you can watch the order in which things happen.
public class TwoResources {
static class Resource implements AutoCloseable {
private final String name;
Resource(String name) {
this.name = name;
System.out.println("opening " + name);
}
@Override
public void close() {
System.out.println("closing " + name);
}
}
public static void main(String[] args) {
try (Resource a = new Resource("a"); Resource b = new Resource("b")) {
System.out.println("using " + a.name + " and " + b.name);
}
System.out.println("done");
}
}When you run it, the output is:
opening a
opening b
using a and b
closing b
closing a
doneWhy Resources Close in Reverse Order
Java opens the resources from left to right and closes them from right to left. The last resource opened is the first one closed.
This order makes sense because a later resource often depends on an earlier one. Suppose b writes its data through a. If a closed first, b could not finish its work. When b closes first, it can finish cleanly before the thing it depends on goes away.
A Real Example: Copying a File
This method copies a text file line by line. It uses a reader for the input file and a writer for the output file.
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
public class CopyFile {
static void copy(Path from, Path to) throws IOException {
try (BufferedReader in = Files.newBufferedReader(from);
BufferedWriter out = Files.newBufferedWriter(to)) {
String line;
while ((line = in.readLine()) != null) {
out.write(line);
out.newLine();
}
}
}
public static void main(String[] args) throws IOException {
Path source = Path.of("input.txt");
Files.writeString(source, "first line\nsecond line\n");
copy(source, Path.of("output.txt"));
System.out.println(Files.readString(Path.of("output.txt")));
}
}Without try-with-resources, you would need nested finally blocks to close both files safely. Here the writer closes first and then the reader, even if an IOException happens partway through.
Key Points
| Rule | What it means |
|---|---|
| Separate with `;` | Each resource declaration ends with a semicolon |
| Open order | Left to right, as written |
| Close order | Right to left, the reverse of opening |
| Partial failure | Resources already opened are still closed |
Exercise
A try-with-resources statement declares three resources: x, then y, then z. The body finishes normally. In what order are they closed?
Show answer
z is closed first, then y, then x. Resources always close in the reverse of the order in which they were declared.
Exercise
In the TwoResources program, what would print if the constructor for b threw an exception?
Show answer
"opening a" prints, then "closing a" prints, because a was already opened. The body never runs, b is never closed because it was never created, and the exception then propagates out of main.