java - 执行器池未处理所有项目
问题描述
我需要执行一些操作 5000 万个项目。我写了下面的代码
AtomicInteger failCounter = new AtomicInteger(0);
long start = System.currentTimeMillis();
ExecutorService es = Executors.newFixedThreadPool(30);
List<String> allids = getItems();//50 million items from db
log.info(getAction() + " Total items found: " + allids.size());
allids.stream().forEach(s -> {
es.execute(new MyRunnable(s, failCounter));
});
es.shutdownNow();
try {
if (!es.awaitTermination(100, TimeUnit.SECONDS)) {
System.out.println("Still waiting...");
System.exit(0);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Exiting normally...");
log.info("counter: " + failCounter.get());
public class MyRunnable implements Runnable {
private final String id;
private final AtomicInteger failCounter;
RollupRunnable(String id, AtomicInteger failCounter) {
this.id = id;
this.failCounter = failCounter;
}
@Override
public void run() {
try {
//perform some action
} catch (Exception exception) {
failCounter.getAndIncrement();
log.error(
"Error in calling " + getAction() + " for id: " + id + " of :" + this.getClass()
.getSimpleName(),
exception);
}
}
}
但执行者在处理前 30 个项目后存在。
难道我做错了什么。
解决方案
而不是es.shutdownNow();
使用es.shutdown();
shutDownNow()
停止所有任务的处理,包括那些甚至没有执行的任务。
这就是为什么并非所有项目都由 Executor 框架执行的原因。
推荐阅读
- python - pypyodbc 查询中的字符串无法识别
- java - Apache Commons HashCodeBuilder:数字类型的 null 与零
- python - 有没有办法在 Python 中安装一个名为 google 的模块?
- c++ - 在一行上流式传输多个变量?
- python - 制表 Python 字典
- pandas - IOError although file name is correct and in the same folder
- javascript - 使用对象数组及其值。npm 模块/库/类
- reactjs - useEffect 顺序和定义何时运行
- docker - Docker-compose - npm 错误!在 client@0.1.0 启动脚本失败
- java - 为什么使用 Spring Mail 缺少附件?(科特林)