我有一个返回 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/