I am creating a lot of temp directories for batch processing using this:
Path tmp = Files.createTempDirectory("tmp-images");
The directory may contain 1-50 image files. I am deleting the directory after processing using Apache FileUtils
:
FileUtils.deleteDirectory(tmp.toFile());
The directory is deleted but I am running into "too many open files". lsof
is giving me this:
java DIR 253,0 6 136899239 /opt/tomcat/temp/tmp-images1570439806870910607 (deleted)
java DIR 253,0 6 136899237 /opt/tomcat/temp/tmp-images2456811184361231168 (deleted)
java DIR 253,0 6 136899237 /opt/tomcat/temp/tmp-images2456811184361231168 (deleted)
java DIR 253,0 6 136899238 /opt/tomcat/temp/tmp-images8109733179118089091 (deleted)
java DIR 253,0 6 69527104 /opt/tomcat/temp/tmp-images8763413559313243911 (deleted)
java DIR 253,0 6 136927313 /opt/tomcat/temp/tmp-images8168355305097994981 (deleted)
How to delete nio2 temp directory without open file handle?
try to identify the source of the problem. - 1 - Check the current limits. - 2 - Check the limits of a running process. - 3 - Tracking a possible file descriptors leak.
I've found the bug. I've used this:
List<Path> result = Files.list(tmp).collect(Collectors.toList());
This leaves the directory OPEN two times!
The right way is actually this:
List<Path> result;
try(Stream<Path> stream = Files.list(tmp)){
result = stream.collect(Collectors.toList());
}
java doc:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With