Sub topic 11
Why Closing Resources Is Hard
A resource is something your program borrows from the operating system and must give back when it is done. Files, network connections, and database connections are all resources. You "give back" a resource by calling its close() method.
This chapter shows why closing resources matters. It also shows why closing them by hand is easy to get wrong.
Why You Must Close Resources
The operating system lets each program keep only a limited number of resources open at once. A file handle is the operating system's record of one open file. If your program opens files and never closes them, it eventually runs out of handles. Then it cannot open anything new.
Leaving resources open causes other problems too:
| Problem | What happens |
|---|---|
| Too many open files | New `open` calls fail with an error |
| Unsaved data | Data waiting in memory may never reach the file |
| Locked files | Other programs may not be able to use the file |
| Wasted connections | A database may refuse new connections |
A resource that is never closed is called a leak.
The Leak Hidden by an Exception
Here is a method that looks correct:
import java.io.BufferedReader;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
public class LeakyRead {
static String firstLine(Path path) throws IOException {
BufferedReader reader = Files.newBufferedReader(path);
String line = reader.readLine();
reader.close();
return line;
}
}The problem is readLine(). If it throws an IOException, Java leaves the method right away. The line reader.close() never runs, so the file stays open.
Manual Cleanup in finally
You learned earlier that a finally block always runs. So you can move close() into finally:
import java.io.BufferedReader;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
public class ManualClose {
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 = Path.of("notes.txt");
Files.writeString(file, "hello\nworld\n");
System.out.println(firstLine(file));
}
}Running it prints hello. Now the file closes even if readLine() fails. The fix took a lot of extra work, though:
- You must declare
readeroutside thetrysofinallycan see it. - You must set it to
nullfirst and check fornull, because opening the file might fail. - You must remember to do all of this every single time.
With two or three resources, you need nested try and finally blocks, and the code gets hard to read. Java has a better tool for this called try-with-resources. The next chapters cover it.
Exercise
In the LeakyRead example, why does the file stay open if readLine() throws an IOException?
Show answer
The exception makes Java leave the method immediately, so the line reader.close() is never reached. Nothing else closes the file, so it leaks.
Exercise
In ManualClose, why is reader set to null before the try block and checked for null in finally?
Show answer
If Files.newBufferedReader fails, reader is never assigned. The finally block still runs, and without the null check it would call close() on null and throw a NullPointerException.