gpt4 book ai didi

Java 8 读取文件列表,但文件保持打开状态,直到服务器卡住

转载 作者:搜寻专家 更新时间:2023-10-31 19:42:56 29 4
gpt4 key购买 nike

这是我在调度程序上的 tomcat 服务器上运行的代码副本。当我检查服务器的状态时,我可以看到打开文件的数量在增加

这是用来检查打开文件的命令

sudo lsof -p $(pidof java) | grep“DIR” | wc -l

这是包装在单元测试中的代码示例。

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;

import org.junit.Test;

public class OpenFilesTest {

@Test
public void FileRemainOpen() throws IOException {
String path = "/data/cache/hotels/from_ivector";

List <String> files = new ArrayList<String>();

Files.list(Paths.get(path))
.filter(Files::isRegularFile)
.forEach(file -> {
String name = file.getFileName().toString().toLowerCase();
if (name.endsWith(".csv") || name.endsWith(".txt")) {
name = file.getFileName().toFile().getName();
files.add(name);
}
});
}
}

最终资源耗尽,服务器卡住。

最佳答案

完成后您应该关闭Stream。来自 Files.list 的 Javadoc :

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

例子:

try (Stream<Path> stream = Files.list(directory)) {
// use the stream...
}

关于Java 8 读取文件列表,但文件保持打开状态,直到服务器卡住,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53895755/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com