Card 08/ 10
All 10 cards
ConceptDifficulty: Advanced1 min
try-with-resources, and the finally Block It Replaces
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.
BufferedReader in = null;
try {
in = Files.newBufferedReader(path);
return in.readLine();
} finally {
if (in != null) { in.close(); }
}Declaring the resource inside the try brackets makes Java responsible for closing it. Anything whose type implements AutoCloseable may go there.
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.