The too many open files solution appears in stream classes such as files.list

Problem scenario

In the background code of the blog, the design without database is adopted, and all information is based on the file system. When it comes to traversing some file information, the java.nio.file.files class and files.list are used for traversal. However, for stream methods such as files.list, if the resource is not closed, an error of too many open files will appear over time.

Solution

Use try with resource to automatically free resources.

Not improved:

...
Files.list(path).forEach(...)
...

Improved writing:

try (Stream<Path> fileList = Files.list(path)) {
    fileList.forEach(...)
} catch (Exception a) {
    ......
}

In this way, the open files will be automatically closed when using files.list to prevent errors. Similarly, it can also be used on other classes that inherit autoclosable, and subsequent problems will be sorted out.

Conclusion

The efficiency and rationality of the code still need to be considered, otherwise the preliminary test can’t see the problem, and it’s too late to regret for a long time.

Read More: