Sub topic 16
Reusing Existing Variables as Resources
In the last few chapters, every resource was created inside the parentheses of the try. Sometimes you already have the resource in a variable, though. A method might receive it as a parameter, or you might have built it a few lines earlier. Since Java 9, you can hand that existing variable straight to try-with-resources. This chapter shows how that works, the one rule you must follow, and the mistakes to avoid.
The Old Way: Declaring a Second Variable
Before Java 9, the parentheses of a try had to contain a full declaration. A declaration names a type and a new variable, like BufferedReader r = .... If you already had a reader, you had to copy it into a new variable just to satisfy the compiler.
import java.io.BufferedReader;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
public class OldStyle {
static void printAll(Path path) throws IOException {
BufferedReader reader = Files.newBufferedReader(path);
try (BufferedReader r = reader) {
String line;
while ((line = r.readLine()) != null) {
System.out.println(line);
}
}
}
}This works, but now you have two names, reader and r, for the same object. It is easy to use the wrong one, and the extra line adds nothing.
The Java 9 Way: Just Name the Variable
From Java 9 on, you can put the variable name by itself inside the parentheses:
import java.io.BufferedReader;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
public class ExistingResource {
static void printAll(Path path) throws IOException {
BufferedReader reader = Files.newBufferedReader(path);
try (reader) {
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
}
}
}The behavior matches the old version. When the block ends, normally or with an exception, Java calls reader.close(). The only change is that you skip the copy.
A Complete Program You Can Run
The file example needs a real file. This program uses a small homemade resource instead, so you can run it anywhere.
public class ExistingVariableDemo {
static class Connection implements AutoCloseable {
private final String name;
Connection(String name) {
this.name = name;
System.out.println("open " + name);
}
void send(String message) {
System.out.println(name + " sends: " + message);
}
@Override
public void close() {
System.out.println("close " + name);
}
}
public static void main(String[] args) {
Connection conn = new Connection("db");
try (conn) {
conn.send("hello");
}
System.out.println("after try");
}
}Output:
open db
db sends: hello
close db
after tryThe connection was created outside the try and closed automatically at the end of it.
The Rule: Final or Effectively Final
You cannot put just any variable in the parentheses. It must be final or effectively final.
- A final variable is declared with the
finalkeyword. It can be given a value once and never changed. - An effectively final variable has no
finalkeyword, but your code never gives it a new value after the first one. The compiler sees that it never changes and treats it as if it were final.
The rule exists for a simple reason. Java has to close the same object you used in the block. If the variable could point to a different object halfway through, Java could close the wrong one, and the first one would never be closed.
This code does not compile:
public class NotEffectivelyFinal {
static class Connection implements AutoCloseable {
@Override
public void close() {
System.out.println("closed");
}
}
public static void main(String[] args) {
Connection conn = new Connection();
conn = new Connection(); // second assignment
try (conn) { // compile error here
System.out.println("body");
}
}
}Because conn gets a value twice, it is not effectively final, and the compiler rejects the try (conn) line. The same thing happens if you assign to conn inside the try block or anywhere after it in the method. Any second assignment, anywhere, breaks the rule.
Mixing Existing Variables and New Declarations
You can list several resources, separated by semicolons, just as in the chapter on multiple resources. Existing variables and new declarations can be mixed freely. The reverse closing order still applies: the last resource listed closes first.
public class MixedResources {
static class Res implements AutoCloseable {
private final String name;
Res(String name) {
this.name = name;
}
@Override
public void close() {
System.out.println("closing " + name);
}
}
public static void main(String[] args) {
Res first = new Res("first");
final Res second = new Res("second");
try (first; second; Res third = new Res("third")) {
System.out.println("working");
}
}
}Output:
working
closing third
closing second
closing firstGotchas to Watch For
The variable outlives the resource
A resource declared inside the parentheses goes out of scope when the try ends, so you cannot touch it afterward. An existing variable stays in scope, which means you can still call methods on it after it has been closed. With a real BufferedReader, calling readLine() after the block throws an IOException with the message "Stream closed". The compiler will not warn you, so treat the variable as finished once the block ends.
Leaks before the try begins
The automatic close only covers what happens after the try starts. Look at this order:
public class LeakRisk {
static class Res implements AutoCloseable {
@Override
public void close() {
System.out.println("closed");
}
}
public static void main(String[] args) {
Res res = new Res();
int risky = Integer.parseInt("oops"); // throws here
try (res) {
System.out.println(risky);
}
}
}parseInt throws a NumberFormatException before the try is reached, so close() is never called and "closed" is never printed. Keep the gap between creating a resource and entering the try as small as possible. Ideally, nothing that can throw sits between them.
A null variable is skipped
If the variable is null, the block still runs, and Java simply does not call close(). It does not throw a NullPointerException at the end. That can be handy, but your code inside the block must still check for null before using the variable.
Choosing a Style
| Situation | Recommended form |
|---|---|
| You create the resource right where you use it | `try (Res r = new Res())` |
| The resource arrives as a method parameter | `try (param)` |
| You built the resource earlier and never reassign it | `try (existing)` |
| You must support Java 8 or older | `try (Res r = existing)` |
When you can choose, declaring the resource inside the parentheses is still the safest option. It leaves no gap before the try and no variable left over afterward. The Java 9 form is best when the resource already exists, especially when it comes in as a parameter.
Exercise
A method has BufferedReader reader = Files.newBufferedReader(path); and later, after the try block, the line reader = null;. Will try (reader) { ... } compile? Why or why not?
Show answer
No. Assigning null to reader gives it a second value, so it is no longer effectively final. Any reassignment anywhere in the method breaks the rule, even one after the try block. Remove the reassignment, or use a separate variable.
Exercise
In try (a; Res b = new Res("b"); c) { }, where a and c are existing effectively final resources, in what order are they closed?
Show answer
c, then b, then a. Resources always close in reverse order of how they are listed, whether they are existing variables or new declarations.
Exercise
Rewrite try (Connection c = conn) { c.send("hi"); } using the Java 9 form, assuming conn is never reassigned.
Show answer
try (conn) { conn.send("hi"); } The extra variable c is no longer needed, and conn is closed automatically when the block ends.