首頁  >  文章  >  Java  >  如何使用CompletionService來優化等待future清單並有效率地處理異常?

如何使用CompletionService來優化等待future清單並有效率地處理異常?

Patricia Arquette
Patricia Arquette原創
2024-10-25 19:58:29928瀏覽

How can CompletionService be used to optimize waiting for a list of futures and handle exceptions efficiently?

使用CompletionService 最佳化Future 清單等待

使用future 清單時,高效等待其完成或處理異常至關重要的延遲。

假設您有以下返回future 列表的方法:

List<Future<O>> futures = getFutures();

要等待完成或捕獲異常,一個簡單的方法可能是:

wait() {
  for(Future f : futures) {
    try {
      f.get();
    } catch(Exception e) {
       //Specific exception handling
       //Exception in a future, stop waiting
       return;
    }
  }
}

但是,無論先前的future 是否有異常,此方法都會等待每個future。

解決方案是使用 CompletionService 來接收可用的 future。如果發生異常,您可以取消其他任務:

Executor executor = Executors.newFixedThreadPool(4);
CompletionService<SomeResult> completionService = new ExecutorCompletionService<SomeResult>(executor);

//Submit tasks
for(int i = 0; i < 4; i++) {
  completionService.submit(() -> {
    ...
    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++;
    ... //Process result
  } catch(Exception e) {
    //Log and set error flag
    errors = true;
  }
}

在這種方法中,任務會提交給執行器,並透過完成服務接收已完成的任務。如果接收到的任務發生異常,則 while 迴圈終止,您可以使用執行器的 shutdownNow() 方法取消任何剩餘的任務。

以上是如何使用CompletionService來優化等待future清單並有效率地處理異常?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn