java - Java 8 读取文件列表,但文件在服务器冻结之前仍然打开使用资源
问题描述
这是我在调度程序上的 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
在完成后关闭。来自的Javadoc Files.list
:
返回的流包含对打开目录的引用。通过关闭流来关闭目录。
例子:
try (Stream<Path> stream = Files.list(directory)) {
// use the stream...
}
推荐阅读
- gradle - 使用 TeaVM 编译时出现 IllegalArgumentException
- sqlite - window.sqlitePlugin 未定义 - 但已安装 sqlite
- python - 是否可以将对象字段直接初始化为 __init__ 关键字参数?
- oracle - 预言机序列是否有可能生成小于最新生成值的值
- list - 在 DB2 存储过程中传递一个列表/数组
- .htaccess - 获取要在特定 URL 上忽略的重写规则
- c++ - 创建具有受限属性的类型
- python - 将 json 字符串图像转换为 numpy 二维数组
- openssl - Wireshark 中的 .pem 文件格式
- neo4j - 我们可以使密码字段查询不区分大小写吗