从 completablefuture 中检索 runnable 的实例

Retrieve the instance of runnable from completablefuture

我是 运行 使用 ExecutorService 并使用 CompletableFuture 整理所有结果的可运行列表。我想将 CompletableFuture 运行 的哪个实例关联到特定的可运行对象。

这是实际代码

public static void runTasks(final List<Runnable> tasks, final int threadCount) {
    final ExecutorService es = Executors.newFixedThreadPool(threadCount);
    final CompletableFuture<?>[] futures = tasks.stream()
            .map(task -> CompletableFuture.runAsync(task, es))
            .toArray(CompletableFuture[]::new);
    try {
        CompletableFuture.allOf(futures).join();
        es.shutdown();
    } catch (Exception e) {
        System.exit(1);
    }
}

我将结果存储在 futures 变量中 CompletableFuture<?>[] futures

有没有办法获取结果存储在 future 实例中的 runnable 的 class 名称?

我正在尝试按如下方式打印单个任务结果:

for (CompletableFuture future : futures) {
    final boolean taskCompletedSuccessfully = future.isDone() && !(future.isCompletedExceptionally() || future.isCancelled());
    LOGGER.info("Task completion status for {} : {}", <runnable class name>, (taskCompletedSuccessfully ? "SUCCESSFUL" : "FAILED"));
}

无法检索有关 Runnable 的任何信息,因为 CompletableFuture 没有对它的任何引用。

因此,您必须在某些 Pair 实现中将 future 和 runnable(或其 class 名称)存储在一起,例如:

final List<Pair<Runnable, CompletableFuture<Void>>> futures = tasks.stream()
        .map(task -> new Pair<>(task, CompletableFuture.runAsync(task, es)))
        .collect(toList());
try {
    CompletableFuture.allOf(futures.stream().map(Pair::getB).toArray(CompletableFuture[]::new)).join();
} catch (Exception e) {
    log.warn("At least one future failed", e);
}
es.shutdown();
futures.forEach(pair -> {
    CompletableFuture<Void> future = pair.getB();
    final boolean taskCompletedSuccessfully = !future.isCompletedExceptionally();
    log.info("Task completion status for {} : {}", pair.getA().getClass().getSimpleName(), (taskCompletedSuccessfully ? "SUCCESSFUL" : "FAILED"));
});

一些注意事项:

  • 如果任何任务失败,allOf() 也会失败。在这种情况下,您可能不想 exit() – 否则您将始终只记录成功的任务;
  • allOf().join()之后,保证isDone()对所有任务都成立,无需检查;
  • isCancelled()(这里不可能)意味着 isCompletedExceptionally()