java - 等待 future 的名单

标签 java multithreading future

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

相关文章:

java - 为什么公共(public)类在 android 开发人员滑动 View 示例中的同一个文件中?

c++ - win32::WaitForSingleObject 期间 Windows 上的 Boost.Thread 断言/崩溃

mysql - Scala Slick : Insert fails with RejectedExecutionException

Java API 连接失败 : PKIX path

java - 如何使用 docx4j 在 word 中添加合并字段?

java - boolean 递归中的 "unreachable statement"

scala - Await#result 抛出的异常

performance - 是否对现代CPU缓存进行了优化以应对不断发展的步伐?跨线程?

java - 数据未存储到领域数据库中

rust - 如何将 future 0.1 迭代器收集到向量中?