- mongodb - 在 MongoDB mapreduce 中,如何展平值对象?
- javascript - 对象传播与 Object.assign
- html - 输入类型 ="submit"Vs 按钮标签它们可以互换吗?
- sql - 使用 MongoDB 而不是 MS SQL Server 的优缺点
我有一个返回 List
future 的方法
List<Future<O>> futures = getFutures();
现在我想等到所有 future 都成功处理完毕,或者任何由 future 返回输出的任务引发异常。即使一个任务抛出异常,等待其他 future 也没有意义。
简单的方法是
wait() {
For(Future f : futures) {
try {
f.get();
} catch(Exception e) {
//TODO catch specific exception
// this future threw exception , means somone could not do its task
return;
}
}
}
但这里的问题是,例如,如果第 4 个 future 抛出异常,那么我将不必要地等待前 3 个 future 可用。
如何解决这个问题?倒计时闩锁会以任何方式提供帮助吗?我无法使用 Future isDone
因为 java doc 说
boolean isDone()
Returns true if this task completed. Completion may be due to normal termination, an exception, or cancellation -- in all of these cases, this method will return true.
最佳答案
您可以使用 CompletionService准备好后立即接收 future ,如果其中一个引发异常,则取消处理。像这样的:
Executor executor = Executors.newFixedThreadPool(4);
CompletionService<SomeResult> completionService =
new ExecutorCompletionService<SomeResult>(executor);
//4 tasks
for(int i = 0; i < 4; i++) {
completionService.submit(new Callable<SomeResult>() {
public SomeResult call() {
...
return result;
}
});
}
int received = 0;
boolean errors = false;
while(received < 4 && !errors) {
Future<SomeResult> resultFuture = completionService.take(); //blocks if none available
try {
SomeResult result = resultFuture.get();
received ++;
... // do something with the result
}
catch(Exception e) {
//log
errors = true;
}
}
我认为如果其中一个引发错误,您可以进一步改进以取消任何仍在执行的任务。
关于java - 等待 future 的名单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19348248/
我正在努力实现下一个目标: 家长: public class Animal { private List relatives; public List getRelatives() {
是否可以创建一个包含不同类型委托(delegate)的列表?例如考虑这两个委托(delegate): class MyEventArg1 : EventArgs {} class MyEventArg
我的问题几乎与 C equivalent to Fortran namelist 相同 关键区别在于我使用的是 C++/17,想知道是否有更符合 C++ 习惯的方式来解决这个问题。 最佳答案 没有相当
我正在使用具有固定线程池大小的全局执行程序服务。我们有一堆相关任务提交执行并等待 future 列表。 最近,我们遇到了 CPU 利用率高的问题,在调试时我发现对 future 列表中的一项调用 ge
我习惯了 Fortran,其中我使用名称列表顺序读入从文件中获取变量。这让我有一个看起来像这样的文件 &inputDataList n = 1000.0 ! This is the first var
为什么TimePicker在 knockout 名单之外工作得很好,但在他身上就不行了。如何在 knockout 中启动? @{ ViewBag.Title = "Index"; } Index
我正在阅读 https://www.nba.com/history/awards/mvp .我尝试按降序打印出名称和计数。 Kareem Abdul-Jabbar: 6 Bill Russell: 5
我想知道如何在 Python 中轻松地从 Fortran 名单文件读取和写入值。 最佳答案 有一个模块叫做f90nml读取/写入 Fortran 名称列表。使用此模块,您可以将名单读入嵌套的 Pyth
我是一名优秀的程序员,十分优秀!