Why does usage of java.nio.files.File::list is causing this breadth-first file traversal program to crash with the “Too many open files” error?

落爺英雄遲暮 提交于 2019-12-05 21:16:01

Seems like the Stream returned from Files.list(Path) is not closed correctly. In addition you should not be using forEach on a stream you are not certain it is not parallel (hence the .sequential()).

    try (Stream<Path> stream = Files.list(path)) {
        stream.map(p -> p.toAbsolutePath().toString()).sequential().forEach(absoluteFileNameQueue::add);
    }

From the Java documentation:

"The returned stream encapsulates a DirectoryStream. If timely disposal of file system resources is required, the try-with-resources construct should be used to ensure that the stream's close method is invoked after the stream operations are completed"

The other answers give you the solution. I just want to correct this misapprehension in your question which is the root cause of your problem

... the directory referenced by p is eligible for garbage collection, so its file descriptor should also become closed.

This assumption is incorrect.

Yes, the directory (actually DirectoryStream) will be eligible for garbage collection. However, that does not mean that it will be garbage collected. The GC runs when the Java runtime system determines that it would be a good time to run it. Generally speaking, it takes no account of the number of open file descriptors that your application has created.

In other words, you should NOT rely on garbage collection and finalization to close resources. If you need a resource to be closed in a timely fashion, then your application should take care of this for itself. The "try-with-resources" construct is the recommended way to do it.


You commented:

I actually thought that because nothing references the Path objects and that their FDs are also closed, then the GC will remove them from the heap.

A Path object doesn't have a file descriptor. And if you look at the API, there isn't a Path.close() operation either.

The file descriptors that are being leaked in your example are actually associated with the DirectoryStream objects that are created by list(path). These objects will become eligible when the Stream.forEach() call completes.

My misunderstanding was that the FD of the Path objects are closed after each forEach invocation.

Well, that doesn't make sense; see above.

But even if it did make sense (i.e. if Path objects did have file descriptors), there is no mechanism for the GC to know that it needs to do something with the Path objects at that point.

Otherwise I know that the GC does not immediately remove eligible objects from the memory (hence the term "eligible").

That really >>is<< the root of the problem ... because the eligible file descriptor objects will >>only<< be finalized when the GC runs.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!