Scrivio Interview library
DebuggingIntermediate6 min read · updated 12 November 2026

A scheduled job uses Files.list(dir) every minute and after a few days fails with Too many open files. What is wrong?

Files.list(dir) returns a Stream that holds an open directory handle, a file descriptor, until the stream is closed, and finishing the stream does not close it. The job never closes it, so every minute one descriptor leaks, and after a few days the process reaches its limit and every new file or socket fails with Too many open files. The fix is to wrap Files.list, and likewise Files.walk, Files.lines and Files.newDirectoryStream, in try-with-resources, and to confirm with lsof or the JVM's open file descriptor metric.

Why this question is asked

A failure that appears only after days of uptime is one of the hardest kinds to diagnose, because nothing in the recent code or traffic changed. Too many open files is a typical example: the error appears in some unrelated place, such as an HTTP client that cannot open a socket, while the real cause is a slow leak elsewhere. Interviewers ask this because it tests whether we know which Java APIs hold operating system resources and how to prove a leak. In this answer, we will recap what a file descriptor is, reproduce the leak, see why the stream does not close itself, fix it, and then confirm the fix with measurements.

1A Quick Recap of File Descriptors

When a process opens a file, a directory, a socket or a pipe, the operating system gives it a file descriptor, a small integer that identifies the open resource. Each process has a limit on how many it may hold at once, set by ulimit -n on Linux and often 1,024 by default for interactive shells, with services commonly raised to 65,536 or more. Once the limit is reached, every attempt to open anything fails with the error EMFILE, which Java reports as an IOException or FileSystemException whose message contains Too many open files.

That is why the symptom often appears far from the cause. The leak uses up descriptors slowly, and whichever code tries to open something after the limit is reached fails, whether it is a log file, a database connection or an outgoing HTTP request.

2Reproducing the Leak

The scheduled job probably looks something like this.

Java
@Scheduled(fixedRate = 60_000)
void importNewFiles() throws IOException {
Files.list(inbox) // opens a directory handle
.filter(p -> p.toString().endsWith(".csv"))
.forEach(this::importFile);
} // stream never closed
// lsof -p <pid> | grep -c inbox
// after 1 hour: 60
// after 1 day: 1440
// after 3 days: 4320 -> beyond a limit of 4096: java.nio.file.FileSystemException: ... Too many open files
Descriptors leaked over time (one per run)
UptimeRunsLeaked descriptorsState with limit 4096
1 hour6060fine
1 day1,4401,440fine, but growing
2 days2,8802,880fine, but growing
3 days4,3204,320every open fails: Too many open files

Each run opens the inbox directory, reads its entries and processes them, and then drops the stream without closing it. One descriptor stays open per run, 1,440 per day. With a limit of 4,096 the process fails after a little under three days, which matches the report of failures after a few days.

3Why the Stream Does Not Close Itself

Most Java streams, such as list.stream(), have nothing to release, so we never think about closing them. The streams returned by Files.list, Files.walk, Files.find and Files.lines are different: they are backed by an open DirectoryStream or file, and their documentation says they must be closed, typically with try-with-resources. Reaching the end of the stream, or a terminal operation like forEach completing, does not close it; only calling close() does, which runs the stream's close handler and releases the descriptor.

It is natural to hope the garbage collector will help, and sometimes it eventually does, because the JDK uses cleaners on some underlying objects. But collection timing depends on heap pressure, not on how many descriptors we hold. A job with a small heap may go days without a collection that reclaims those objects, so we can never rely on GC to release operating system resources.

4The Fix

We wrap the stream in try-with-resources, so it is closed when the block exits, whether normally or because importFile threw.

Java
@Scheduled(fixedRate = 60_000)
void importNewFiles() throws IOException {
try (Stream<Path> files = Files.list(inbox)) {
files.filter(p -> p.toString().endsWith(".csv"))
.forEach(this::importFile);
} // directory handle released here
}
// Same rule for the explicit DirectoryStream API, which also supports glob filters
try (DirectoryStream<Path> ds = Files.newDirectoryStream(inbox, "*.csv")) {
for (Path p : ds) importFile(p);
}

It is also worth checking importFile itself. If it opens each CSV with Files.newBufferedReader, Files.lines or a FileInputStream, those must be closed too, or each imported file leaks another descriptor and the job fails even sooner. Leaks tend to come in families, so a reviewer should search the codebase for every call to these methods that is not inside a try-with-resources header; static analysis tools such as Error Prone and SonarQube have rules that flag unclosed streams and resources.

5Confirming the Diagnosis and the Fix

We do not want to guess. On Linux, lsof -p <pid> lists every descriptor the process holds, and counting entries that point at the inbox directory shows the leak directly; ls /proc/<pid>/fd | wc -l gives the total quickly. Inside the JVM, the OperatingSystemMXBean on Unix platforms reports open and maximum file descriptor counts, and Spring Boot with Micrometer publishes them as process.files.open and process.files.max. A graph of process.files.open that climbs in a straight line, one step per minute, is the leak's fingerprint. After deploying the fix, the same graph should be flat, rising and falling with real work only. We also add an alert when open descriptors reach, say, 80 percent of the maximum, so the next leak is caught days before it causes an outage.

6Follow-up questions

Would raising the ulimit fix the problem?

It only delays it. With a limit of 65,536 the same leak takes about 45 days instead of 3, which makes it even harder to connect to its cause. Raising the limit is reasonable for services that really need many concurrent connections, but a leak needs to be fixed in code.

Why does the error appear in unrelated code, such as the HTTP client?

Because descriptors are shared by the whole process. Once the leak has used them up, the next thing to open a file or socket fails, whichever component that happens to be. The stack trace shows the victim, not the cause, which is why we look at what the open descriptors actually point to with lsof.

7Conclusion

In this answer, we saw that Files.list returns a stream backed by an open directory handle that is released only when the stream is closed, so a job that runs every minute without closing it leaks 1,440 descriptors a day until the process hits its limit. Wrapping Files.list, Files.walk, Files.lines and Files.newDirectoryStream in try-with-resources fixes it, and lsof together with the process.files.open metric proves both the leak and the fix.

What to say in the interviewAbout 90 seconds aloud

Open with

Files.list returns a Stream, but unlike a stream over a collection it is backed by an open directory handle, a file descriptor, and it keeps that descriptor until the stream is closed.

Then, if they want more

Finishing the stream with forEach does not close it, and we cannot count on garbage collection to clean it up.

So if the job calls Files.list every minute without closing it, it leaks one descriptor per run, 1,440 a day, and after a few days the process hits its ulimit and anything that opens a file or a socket fails with Too many open files.

The error often shows up in unrelated code, which is a clue that it is a leak. The fix is try-with-resources around the stream: try (Stream<Path> files = Files.list(dir)) { ... }. The same applies to Files.walk, Files.find, Files.lines and Files.newDirectoryStream, and I would also check that whatever processes each file closes its own reader.

To confirm, I would look at lsof -p on the process and see hundreds of entries for that directory, or watch the JVM's open file descriptor count, which Micrometer exposes as process.files.open; a straight line going up by one per minute is the leak.

After the fix that graph should be flat, and I would add an alert at around 80 percent of the maximum.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "A scheduled job uses Files.list(dir) every minute and after a few days fails with Too...": https://scrivio-interview-library.netlify.app/java/io-and-nio/49e305bdc7/