Sub topic 14
Managing Multiple Resources
Real programs often need more than one resource at a time. A file copy program reads from one file and writes to another. A database program may open a connection and then a statement on that connection. Each of these is a resource. A resource is an object that holds something from outside your program, such as an open file, and must be closed when you are done.
The previous chapter showed how try-with-resources closes one resource for you. This chapter shows how to manage several resources in one statement. It covers the order Java opens and closes them, and what happens when one of them fails to open.
Declaring More Than One Resource
You can put several resources inside the parentheses of a single try. Separate them with a semicolon (;).
public class TwoResources {
static class Res implements AutoCloseable {
private final String name;
Res(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 (Res a = new Res("a"); Res b = new Res("b")) {
System.out.println("using a and b");
}
System.out.println("done");
}
}Run it and you will see this output:
opening a
opening b
using a and b
closing b
closing a
doneEach resource still needs to implement AutoCloseable. AutoCloseable is an interface with one method, close(), that try-with-resources calls for you. The Res class above implements it, so Java knows how to close it.
The close() method in Res does not declare throws Exception. That means the compiler does not force us to catch anything, so the example needs no catch block.
The Rule: Close in Reverse Order
Look at the output again. Java opened a first and b second. It closed b first and a second. This is called reverse order. The last resource opened is the first one closed.
Why does Java do this? Later resources often depend on earlier ones. Think of a database: you open a connection first, then a statement that uses the connection. If the connection closed first, the statement would lose what it depends on and could fail while closing. Closing in reverse order means each resource closes while the things it depends on are still open.
A stack of plates works the same way. You put plates on top, and you take them off from the top. The last plate you set down is the first one you pick up.
A Real Example: Copying a File
Here is a practical program. It reads lines from one file and writes them into another. It uses two resources: a BufferedReader for reading and a BufferedWriter for writing.
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 {
public static void main(String[] args) throws IOException {
Path source = Path.of("input.txt");
Path target = Path.of("output.txt");
// Create a small input file so the example runs on its own.
Files.writeString(source, "line one\nline two\n");
try (BufferedReader reader = Files.newBufferedReader(source);
BufferedWriter writer = Files.newBufferedWriter(target)) {
String line;
while ((line = reader.readLine()) != null) {
writer.write(line);
writer.newLine();
}
}
System.out.println(Files.readString(target));
}
}This program needs Java 11 or later because it uses Path.of and Files.writeString.
When the try block ends, Java closes writer first and then reader. Closing the writer also flushes it. Flushing means pushing any text still waiting in memory out to the file. That is why Files.readString(target) can print both lines afterward.
It is common to put each resource on its own line, as shown here. The code is easier to read, and you can see at a glance how many resources the statement manages.
What If a Resource Fails to Open?
Sometimes the second resource cannot be opened. Maybe the output file is in a folder you cannot write to. What happens to the first resource, which is already open?
Java handles this for you. It closes only the resources that opened successfully, still in reverse order. A resource that never opened is never closed, because there is nothing to close. Then the exception moves on to your catch block, if you wrote one.
public class OpenFailure {
static class Res implements AutoCloseable {
private final String name;
Res(String name, boolean fail) {
System.out.println("opening " + name);
if (fail) {
throw new IllegalStateException("cannot open " + name);
}
this.name = name;
}
@Override
public void close() {
System.out.println("closing " + name);
}
}
public static void main(String[] args) {
try (Res a = new Res("a", false);
Res b = new Res("b", true);
Res c = new Res("c", false)) {
System.out.println("body runs");
} catch (IllegalStateException e) {
System.out.println("caught: " + e.getMessage());
}
}
}Output:
opening a
opening b
closing a
caught: cannot open bNotice these four points:
aopened, so it was closed.bthrew an exception while opening, so it was never closed.cwas never even created, because Java stopped atb.- The body never ran.
Also notice that closing a prints before caught: .... Try-with-resources always closes resources first and runs the catch block after. By the time your catch code runs, every resource that opened is already closed.
One Statement or Nested Statements?
You could also write one try inside another. Both versions close resources correctly.
public class NestedVersion {
static class Res implements AutoCloseable {
private final String name;
Res(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 (Res a = new Res("a")) {
try (Res b = new Res("b")) {
System.out.println("using a and b");
}
}
}
}The output is the same as the first example. Here is how the two styles compare:
| Style | When to use it | Downside |
|---|---|---|
| One `try` with several resources | The resources are used together for the whole block | None for most cases |
| Nested `try` statements | You need to do some work with `a` before opening `b`, or close `b` early | More indentation, harder to read |
Most of the time, a single statement with several resources is the clearer choice.
A Common Trap: Hidden Resources
Beginners sometimes wrap one resource inside another on a single line:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class HiddenResource {
static String firstLine(String path) throws IOException {
try (BufferedReader reader = new BufferedReader(new FileReader(path))) {
return reader.readLine();
}
}
}Only reader is declared as a resource here. The FileReader is created inside it, and Java does not track it on its own. In normal runs this works, because closing a BufferedReader also closes the reader inside it. But if the BufferedReader constructor failed after the FileReader opened, the file would stay open.
The safer habit is to give each resource its own variable:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class SeparateResources {
static String firstLine(String path) throws IOException {
try (FileReader file = new FileReader(path);
BufferedReader reader = new BufferedReader(file)) {
return reader.readLine();
}
}
}Now Java tracks both. If anything goes wrong, whatever opened gets closed. Closing a reader twice is harmless for the standard Java readers, so this extra safety costs nothing.
Summary
- Put several resources in one
try (...), separated by semicolons. - Java opens them from left to right and closes them in reverse order.
- If a resource fails to open, Java closes only the ones that already opened.
- All resources close before
catchandfinallyrun. - Declare each resource as its own variable so Java can track every one.
Exercise
A try-with-resources statement declares three resources in this order: conn, stmt, rs. The body finishes normally. In what order are they closed?
Show answer
rs first, then stmt, then conn. Resources close in reverse order of declaration.
Exercise
In try (Res a = new Res("a"); Res b = new Res("b"); Res c = new Res("c")), the constructor for c throws an exception. Which resources are closed, and in what order? Does the body run?
Show answer
b is closed, then a. c is never closed because it never opened. The body does not run, because the exception happened while the resources were being opened.
Exercise
Rewrite try (BufferedWriter w = new BufferedWriter(new FileWriter("out.txt"))) { w.write("hi"); } so that both writers are tracked as resources.
Show answer
try (FileWriter file = new FileWriter("out.txt"); BufferedWriter w = new BufferedWriter(file)) { w.write("hi"); }. Java now closes w first and then file, and file still gets closed if the BufferedWriter constructor fails.