我有一个方法,它返回一个 List
的 future。
List<Future<O>> futures = getFutures();
现在我希望等待直到所有的future都成功处理完毕,或者任何一个由future返回输出的任务抛出异常。即使有一个任务抛出异常,也没有必要等待其他futures。
简单的方法是
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变为可用。
该如何解决?计数器 latch 能帮上忙吗?由于Java文档上说无法使用Future的 isDone
方法,所以我不知道该怎么做。
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.
ExecutionService
实例,将它们提交到该实例中,然后立即关闭服务并在其上使用awaitTermination()
。 - millimoosetry..finally
中以确保计数器也被减少,那么您可以使用CountDownLatch
。 - millimoose