BackendBench
Coffee
Spot the Bug #28

Counting lines and keeping the file open

A medium Java puzzle in the resource leaks family. One line below contains a real bug. Try to spot it first, then read why it fails and how to fix it.

mediumResource leaksbuggy line: 6

Highlighted: line 6. Play this one as a puzzle without the answer.

What is wrong

Files.lines returns a Stream that holds an open file handle until it is closed. A terminal operation does not close it. Calling this method in a loop leaks one handle per call.

The fix

try (var lines = Files.lines(p)) { return lines.filter(l -> !l.isBlank()).count(); }

How to avoid it next time

Streams from Files.lines, Files.list, Files.walk and Files.find must be closed with try-with-resources.

Want the background? Read NIO.2: Path and Files in practice in the Java concepts library.

About resource leaks

Files, streams, sockets, connections and statements hold operating system handles that the garbage collector will not release promptly. A leak often shows up only in production after hours of load as too many open files or an exhausted connection pool.

In code review: Every constructor of a closeable type should sit in a try-with-resources header. Check the exceptional path as well as the normal one.

More puzzles in this family

๐Ÿž Play today's puzzleAll 132 bugsโ† #27#29 โ†’

Frequently asked questions

What is the bug in "Counting lines and keeping the file open"?

Files.lines returns a Stream that holds an open file handle until it is closed. A terminal operation does not close it. Calling this method in a loop leaks one handle per call. The faulty line is line 6: return Files.lines(p).filter(l -> !l.isBlank()).count();

How do I fix it?

Replace it with: try (var lines = Files.lines(p)) { return lines.filter(l -> !l.isBlank()).count(); }. Streams from Files.lines, Files.list, Files.walk and Files.find must be closed with try-with-resources.

How do I catch resource leaks in code review?

Every constructor of a closeable type should sit in a try-with-resources header. Check the exceptional path as well as the normal one.

Is there a new puzzle every day?

Yes. The daily Spot the Bug puzzle picks one of these snippets for each UTC day, with the difficulty set by the weekday. Your streak is stored only in your browser.

More tools you might need