Video in progress

Strong Junior 📁 IO and NIO

What is the problem in this method, and how does it show up on prod?

public String firstLine(Path p) throws IOException {
    BufferedReader br = new BufferedReader(new FileReader(p.toFile()));
    String line = br.readLine();
    if (line == null) {
        return "";
    }
    br.close();
    return line;
}

The file stream is never closed: whether an exception is thrown or not, the file descriptor stays open. After many calls the process hits the OS limit and fails with Too many open files, unable to open a new file or socket.

📖 Answer

There is a leak in two places:

  • if the file is empty, return "" never reaches close();
  • if readLine() throws an exception, it is not closed either.

The GC may eventually collect the object, but finalizers are deprecated in Java 9+ and there is no guarantee when the descriptor will be released.

On prod it looks like this: the application works fine for a few hours, then java.io.IOException: Too many open files starts appearing. And the interesting part is that the error doesn't come from reading a file; it comes when opening a new HTTP connection or DB connection. A socket is a file descriptor too.

The fixed version:

public String firstLine(Path p) throws IOException {
    try (BufferedReader br = Files.newBufferedReader(p)) {
        String line = br.readLine();
        return line == null ? "" : line;
    }
}

To check on Linux: ls /proc/<pid>/fd | wc -l or lsof -p <pid>. If the number keeps growing, there is a leak somewhere.