Olav Grønås Gjerde

profile image
Full stack system architect with passion for Unix, Java, Python and databases.
Twitter @olavgg
3 years ago

Java NIO file descriptor leak issue with Files.list() method

This blog you're reading, is built on Micronaut. And each blog post is stored as a plain text file instead of a database. I just wanted something simple, where I could also easily SSH into the server for modifying and adding new content. However I recently stubled upon a file descriptor leak. I just couldn't figure out how, as everything was wrapped in Java's try with resource.

Anyway using lsof

sudo lsof +D /opt/olavblog

I could see all files that had a file descriptor, and I could see many duplicates. This was because something wasn't properly closed.

Finding the bug ment that I had to use the step by step debugger and check what happened one line after another. In the end I found the faulty line in my code:

Stream<Path> files = Files.list(folderPath)

There is a note in the method documentation mentioning this


 * This method must be used within a try-with-resources statement or similar
 * control structure to ensure that the stream's open directory is closed
 * promptly after the stream's operations have completed.

So the right thing todo is to wrap this in a try with resources statement

try(Stream<Path> files = Files.list(folderPath)){
    files.forEach(filePath -> {