Sub topic 11
Why Closing Resources Is Hard
Your programs often borrow things from the computer, such as files, network connections, and database connections. When you are done with them, you must give them back. This chapter shows why that step matters, how to do it by hand with finally, and why the manual approach is easy to get wrong. The next chapters show the cleaner tool Java gives you.
What Is a Resource?
A resource is something your program opens from the operating system or another outside system and must close when it is finished. The operating system is the software, such as Windows, macOS, or Linux, that manages the computer's files, memory, and network.
Here are some common resources in Java:
| Resource | Java example | What it holds onto |
|---|---|---|
| File reader | `BufferedReader` | An open file handle |
| File writer | `BufferedWriter` | A file handle and unsaved data |
| Network socket | `Socket` | A network connection |
| Database connection | `Connection` | A session on the database server |
| Scanner on a file | `Scanner` | An open file handle |
A file handle is a ticket the operating system gives your program so it can read or write one file. The operating system only hands out a limited number of these tickets to each program.
Why You Must Close Resources
Java has a garbage collector. It is a part of Java that frees memory from objects you no longer use. Many beginners assume the garbage collector also closes files. It does not do this reliably. It runs whenever Java decides to run it, which might be much later or never, and memory is the only thing it is built to free.
If you forget to close a resource, several problems can happen:
- You run out of handles. A program that opens files in a loop and never closes them eventually fails with an error such as "Too many open files".
- Data is lost. Writers keep data in a buffer, a small holding area in memory. The data reaches the file only when the buffer is flushed, and closing the writer flushes it. If you skip
close(), the end of your file can be missing. - Files stay locked. On some systems, such as Windows, other programs cannot delete or change a file while yours still has it open.
- Servers get overloaded. A database allows only a limited number of connections. Leaked connections can block other users.
A resource you forget to close is called a leak. Leaks are hard to spot because the program usually works fine at first and only fails after it has run for a long time.
The Naive Approach and Its Flaw
The simplest idea is to open the resource, use it, then close it:
import java.io.BufferedReader;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
public class LeakyFirstLine {
static String firstLine(Path path) throws IOException {
BufferedReader reader = Files.newBufferedReader(path);
String line = reader.readLine(); // if this throws, close() is skipped
reader.close();
return line;
}
public static void main(String[] args) throws IOException {
Path file = Files.createTempFile("demo", ".txt");
Files.writeString(file, "first line\nsecond line");
System.out.println(firstLine(file));
}
}This code works when everything goes well. Remember from earlier chapters that an exception jumps straight out of the current code. If readLine() throws an IOException, Java leaves the method at once. The line reader.close() never runs, and the file stays open.
Manual Cleanup with finally
You already know that a finally block runs whether the try block finishes normally or throws. That makes it the classic place to close resources:
import java.io.BufferedReader;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
public class FinallyFirstLine {
static String firstLine(Path path) throws IOException {
BufferedReader reader = null;
try {
reader = Files.newBufferedReader(path);
return reader.readLine();
} finally {
if (reader != null) {
reader.close();
}
}
}
public static void main(String[] args) throws IOException {
Path file = Files.createTempFile("demo", ".txt");
Files.writeString(file, "first line\nsecond line");
System.out.println(firstLine(file));
}
}Look at the details:
readeris declared outside thetryblock. A variable declared insidetrycannot be seen infinally.- It starts as
null, which means "no object yet". Opening the file can fail too. If it does,readeris stillnull. - The
finallyblock checksreader != nullbefore callingclose(). Without this check, a failed open would cause aNullPointerExceptioninsidefinally.
That is a lot of code just to read one line, and every part of it is needed.
Problem 1: close() Can Throw Too
close() can fail as well. For example, BufferedReader.close() is declared to throw IOException. Suppose the body of the try throws an exception, and then close() in finally throws a second one. Java can only send one exception out of the method, and it keeps the newer one. The original exception, which tells you what really went wrong, is thrown away.
This small program shows the problem. The fake resource fails both when reading and when closing:
public class LostExceptionDemo {
static class FlakyFile {
String read() {
throw new IllegalStateException("read failed");
}
void close() {
throw new IllegalStateException("close failed");
}
}
public static void main(String[] args) {
FlakyFile file = new FlakyFile();
try {
try {
file.read();
} finally {
file.close();
}
} catch (IllegalStateException e) {
System.out.println("caught: " + e.getMessage());
}
}
}The output is:
caught: close failedThe message "read failed" is gone. When you debug this, you would see only the less important error and could spend a long time looking in the wrong place.
You can work around this by wrapping close() in its own try/catch inside finally. That adds even more code, and you then have to decide what to do with the second error.
Problem 2: Several Resources Multiply the Code
Real tasks often need more than one resource. Copying a file needs an input stream and an output stream. Each one must be closed, even if opening the other one fails. The safe manual version needs one try/finally per resource, nested inside each other:
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
public class CopyDemo {
static void copy(Path from, Path to) throws IOException {
InputStream in = Files.newInputStream(from);
try {
OutputStream out = Files.newOutputStream(to);
try {
byte[] buffer = new byte[8192];
int n;
while ((n = in.read(buffer)) != -1) {
out.write(buffer, 0, n);
}
} finally {
out.close();
}
} finally {
in.close();
}
}
public static void main(String[] args) throws IOException {
Path from = Files.createTempFile("from", ".txt");
Path to = Files.createTempFile("to", ".txt");
Files.writeString(from, "hello, copy");
copy(from, to);
System.out.println(Files.readString(to));
}
}Each resource is opened just before its own try. If opening out fails, the outer finally still closes in. The resources also close in reverse order: out first, then in. This version is correct, but the actual copying is just four lines buried in the middle. Add a third resource and the nesting gets deeper again. Problem 1 also still applies at every level.
Summary of the Difficulties
Closing resources by hand is hard for these reasons:
- Exceptions can skip a plain
close()call. - You must declare variables outside
tryand check fornull. close()can throw and hide the original exception.- Each extra resource needs another nested
try/finally. - The cleanup code is easy to get slightly wrong, and the mistakes often show up only under heavy load.
Java 7 added a feature that handles all of this for you, called try-with-resources. It depends on an interface named AutoCloseable, which is the topic of the next chapter.
Exercise
In the FinallyFirstLine example, why is reader declared outside the try block and set to null, and why does finally check reader != null?
Show answer
A variable declared inside the try block is not visible in finally, so it must be declared outside. It starts as null because opening the file can itself fail. If Files.newBufferedReader throws, reader is still null, and calling close() on it would throw a NullPointerException. The null check prevents that.
Exercise
A method reads a file inside try and closes it in finally. The read throws an IOException with the message "disk error", and then close() throws an IOException with the message "close error". Which message does the caller see, and why is that a problem?
Show answer
The caller sees "close error". An exception thrown from finally replaces the exception that was already leaving the try block. The original "disk error", which explains the real failure, is lost, so debugging becomes harder.
Exercise
Write down the order in which the streams are closed in CopyDemo, and explain what happens to in if Files.newOutputStream(to) throws an exception.
Show answer
out closes first, then in, which is the reverse of the order they were opened. If Files.newOutputStream(to) throws, the inner try is never entered, but the outer try has already started, so the outer finally runs and closes in. No stream leaks.