Files.lines, list, walk and find hold a handle until the stream is closed. On JDK 23 every referenced unclosed stream kept one; only close released it.
A stream that is finished but not closed
Most Java streams are views over memory. A List.stream() holds nothing that needs releasing, so code that never calls close() on a stream is normally correct. java.nio.file.Files breaks that habit with four methods that look like ordinary stream factories:
Files.lines(path)reads a file line by line, lazily.Files.list(dir)lists one directory, lazily.Files.walk(start)andFiles.find(start, depth, matcher)walk a tree, lazily.
Each returned stream holds an open file or directory handle, and the handle is released when the stream is closed, not when the terminal operation finishes. The API documentation says so in each case: the stream returned by Files.lines "encapsulates a Reader", and the documentation recommends try-with-resources "if timely disposal of file system resources is required"; for Files.list the stream "contains a reference to an open directory" which "is closed by closing the stream". count(), collect() and forEach() consume the stream to the end and leave the handle open.
At Belgavi's Book Store a small import service reads help desk exports, one CSV file per batch, with Files.lines(path).filter(...).count() to size the batch and then a second pass to load it. It runs fine in tests. In a long-running process that handles thousands of files a day, it leaks one handle per call until the garbage collector happens to reclaim the streams.
What I measured
The companion Java example has two probes. The first exercises each method with and without try-with-resources and tries to delete the file or directory afterwards. The second counts this process's operating system handles while streams are left open. I ran both on JDK 23.0.2 on Windows 11, compiled with --release 17.
The deletion results were not what folklore predicts. Deleting a file while an unclosed Files.lines stream still held it succeeded, and so did deleting a directory with an unclosed Files.list stream, and a leaf directory after an unclosed Files.walk. The JDK on Windows opens files with sharing modes that allow another caller to delete them, so on this machine a failed delete is not a reliable symptom of a leaked stream. Do not build a test on it.
The handle counts are the reliable symptom. Run with 2,000 iterations, from a baseline of 342 handles:
| Step | Handle count change |
|---|---|
2,000 Files.lines streams, each closed by try-with-resources | +5 |
2,000 Files.lines streams counted but never closed, not kept | +422 |
2,000 Files.list streams counted, never closed, still referenced | +1,998 |
System.gc() twice | -417 |
close the 2,000 Files.list streams | -1,997 |
Three facts follow. Closed streams leave nothing behind beyond a few handles of noise. Unclosed streams that are still referenced hold one handle each, indefinitely, however completely they were consumed. Unclosed streams that become unreachable are eventually released, because the JDK closes the descriptors of unreachable file channels after garbage collection, but only some had been released by the end of the loop, and the rest waited for an explicit GC. The table is the recording in the example's directory. The exact numbers vary from run to run; a second run gave +0, +439, +1,998, -432 and -2,000. The pattern does not vary.
Why the garbage collector is not the fix
Relying on cleanup after collection turns a resource limit into a GC tuning problem. A service with a large heap and little allocation pressure may run for hours between collections that reach the old generation, while the per-process file descriptor limit is fixed. On Linux the default soft limit for an interactive shell is commonly 1,024, and container platforms set their own; once it is reached, every open, socket accept and log rotation in the process fails with "Too many open files", usually far from the code that leaked. On Windows the handle table is much larger, but the leaked handles still pin directory and file objects and show up in tools that list open files.
The referenced case is worse, because the collector can never help. It is common in code that returns a stream from a helper:
List<Path> csvFiles(Path inbox) throws IOException {
return Files.walk(inbox) // leaks: the caller never sees the stream
.filter(p -> p.toString().endsWith(".csv"))
.collect(Collectors.toList());
}
Stream<String> rows(Path file) throws IOException {
return Files.lines(file); // the caller must close this; say so in the name and Javadoc
}The first helper leaks on every call even though its result is a plain list. The second is legitimate only if every caller uses try-with-resources.
The fix and its edge cases
The fix is try-with-resources around every stream from these four methods:
long refunds;
try (Stream<String> lines = Files.lines(file)) {
refunds = lines.filter(l -> l.contains(",refund,")).count();
}
List<Path> found;
try (Stream<Path> paths = Files.walk(inbox)) {
found = paths.filter(Files::isRegularFile).toList();
}Three edge cases matter in practice:
- Exceptions inside the pipeline. The probe throws from a
mapstep on the second row. With try-with-resources the handle is released and the file can be deleted afterwards; without it, an exception is the most common way a stream escapes unclosed, because the code that would have closed it never runs. flatMapover files.Stream.flatMapcloses each inner stream after its contents have been placed into the outer stream, sopaths.flatMap(Files::lines)closes the per-file streams as it goes. The outer stream fromFiles.walkstill needs its own try-with-resources.UncheckedIOException. Lazy streams report I/O errors that happen during traversal asUncheckedIOExceptionfrom the terminal operation, not asIOExceptionfrom the factory method. Catch it where you handle file errors, and remember thatFiles.walkthrows it for a directory that disappears or becomes unreadable mid-walk.
When the file is small and you need all of it, Files.readAllLines and Files.readString read eagerly and close the file before returning. The probe confirms it: after readAllLines, the file was deleted normally. For large files, use the stream and close it.
Finding existing leaks
- Search for
Files.lines(,Files.list(,Files.walk(andFiles.find(and check that each result is either in a try-with-resources header or returned to a caller that is. Static analysis tools in common use flag unclosedAutoCloseableresources, but streams are often exempted because most streams need no closing, so check their settings rather than assuming coverage. - Count handles in a soak test. On Linux, the number of entries in
/proc/<pid>/fdis enough; on Windows the process handle count is what the companion probe reads through PowerShell. Plot it against processed files; a leak is a line that rises with work and drops only at collections. - Add a regression test in the style of the handle probe: open and consume a few thousand streams the way the production code does, and assert that the handle count does not grow by more than a small constant.
Failure modes in review
Returning a lazy stream from a method that sounds eager. A method named readOrders that returns Stream<String> invites callers to treat it like a list. Either return a collection or name it so the obligation is visible, such as openOrderLines.
Storing a stream in a field. A stream held in an object outlives the method that created it, and nothing closes it unless the object is itself AutoCloseable and closed.
Assuming forEach closes. It does not. No terminal operation closes the stream's source.
Parallel streams over Files.lines. These work, and splitting a file-backed stream is supported, but they do not change the closing rule.
Verification
The companion example's run.sh compiles both probes, compares the deletion probe's output with the JDK 23 recording, and runs the handle probe on Windows. The handle probe checks its own pattern rather than exact counts: closed streams add fewer than 50 handles, unclosed referenced streams add at least one per stream minus 50, and closing them removes the same number. It exits with a non-zero status if any of these fail. On other systems the handle probe is skipped, because it reads the Windows handle count; the deletion probe still runs, and its output may differ on file systems where deleting an open file behaves differently.