Card 08/ 10

ConceptDifficulty: Advanced1 min

try-with-resources: Closing Files Automatically

A service runs out of file handles after a fortnight, from one close that sometimes never ran.

try-with-resources is a try that declares a resource, such as a file reader, in brackets after the word try. Java closes the resource on every way out of the block, so it cannot leak. Anything whose type implements AutoCloseable may be declared there.

A service runs out of file handles after a fortnight. Every method that opens a file closes it, and one of them closes it on the line after a call that sometimes throws. The hand-written safe version looks like this:

java
BufferedReader in = null;
try {
    in = Files.newBufferedReader(path);
    return in.readLine();
} finally {
    if (in != null) { in.close(); }
}
correct, and four lines of ceremony, and the null check is easy to leave out

Declaring the resource inside the try brackets makes Java responsible for closing it:

java
try (BufferedReader in = Files.newBufferedReader(path)) {
    return in.readLine();
}

The resource is closed on every way out, a normal return, a break or an exception, and it is closed before any catch or finally you write runs. Several resources may be declared, separated by semicolons, and they are closed in the reverse of the order they were opened.

So there is no reason left to close a resource by hand. Anything holding a file, a socket or a database connection belongs in the brackets, and the leak stops being possible rather than being avoided carefully.