javafilehandle

Java Open File handles for Directories


we realized by inspecting our java application that it seems to collect file handles. When we inspect with lsof what files are being held, they are all directories. We dont use WatchService or anything like that, but we do a bunch of file operations like reading, copying etc.

I am aware of Java try-with-resource for closing opened file streams, but here we talk all about directories. While searching the net, there seems to be no content about how to properly close or leaked directory file handles.

Interestingly we dont have such problems in our staging environment, but there is also less load.

What i know is, that the hardware and shares from which we are copying are quite unstable cifs shares. But the opened folder handles are all on our local disk...

Are you aware of any specific issues, how folder file handles can be leaking, or if there are any ways to protect against this if we know, that the underlying hardware may have problems?

Increasing File Handles


Solution

  • After some heavy debugging, i figured out, that following code leaks to leak:

    Files.list(parent).findAny().isEmpty
    

    The documentation of Files.list says

    The returned stream contains a reference to an open directory. The directory is closed by closing the stream.
    

    I though the stream gets closed with a terminal operation, but that does not seem to be the case, at least with findAny. Thanks to @Andrey pointing me to Files.walk