gpt4 book ai didi

Java CompletableFuture thenCompose 与几个异步任务

转载 作者:行者123 更新时间:2023-11-30 09:59:28 28 4
gpt4 key购买 nike

我有一个由 2 个异步步骤组成的过程。第二步基于第一步的结果运行。该过程在循环中启动。挑战在于第二步是由多个异步任务完成的,这些任务采用第一步迭代的输出。第一步完成后,我想使用第一步结果启动 n 秒步骤。我使用 CompletableFuturethenCompose 编写了这段代码。

它有效,但我发现它非常复杂,我想知道这是否是正确的方法。我特别想知道第二级子任务的管理和使用 CompletableFuture.allOf 使其像一个单一的 CompletableFuture 是否是正确的做法.

public void test() {
// Gather CompletableFutures to wait for them at the end
List<CompletableFuture> futures = new ArrayList<>();

// First steps
for (int i = 0; i < 10; i++) {
int finalI = i;
CompletableFuture<Void> fut = CompletableFuture.supplyAsync(() -> {
logger.debug("Start step 1 - " + finalI);
simulateLongProcessing();// just waits for 1 s
logger.debug("End step 1 - " + finalI);
return "step1 output - " + finalI;
}).thenCompose(s -> {
List<CompletableFuture> subFutures = new ArrayList<>();
// Second step : Launch several sub-tasks based on the result of the first step
for (int j = 0; j < 50; j++) {
final int finalJ = j;
CompletableFuture<String> f = CompletableFuture.supplyAsync(() -> {
logger.debug("Start - step 2 : " + s + " | " + finalJ);
simulateLongProcessing();
logger.debug("End - step 2 : " + s + " | " + finalJ);
return "step2 output - " + s + " | " + finalJ;
});
subFutures.add(f);
}
return CompletableFuture.allOf(subFutures.toArray(new CompletableFuture[0]));
});
futures.add(fut);
}

// Wait for the completion
for (CompletableFuture future : futures) {
future.join();
}
}

最佳答案

不要执行 CompletableFuture.supplyAsync在传递给 thenCompose 的函数中当您可以使用直接的 thenApplyAsync 链接相同的依赖函数时.

通过 thenApplyAsync 链接依赖函数允许您获得 CompletableFuture在第一步完成之前代表这些步骤的实例,因此您可以将它们全部收集到您的 List 中等待它们最后完成,不需要通过 CompletableFuture.allOf 创建复合 future .

public void test() {
// Gather CompletableFutures to wait for them at the end
List<CompletableFuture<?>> futures = new ArrayList<>();

for (int i = 0; i < 10; i++) {
int finalI = i;
CompletableFuture<String> step1 = CompletableFuture.supplyAsync(() -> {
logger.debug("Start step 1 - " + finalI);
simulateLongProcessing();// just waits for 1 s
logger.debug("End step 1 - " + finalI);
return "step1 output - " + finalI;
});
// Second step : Chain several sub-tasks based on the result of the first step
for (int j = 0; j < 50; j++) {
final int finalJ = j;
futures.add(step1.thenApplyAsync(s -> {
logger.debug("Start - step 2 : " + s + " | " + finalJ);
simulateLongProcessing();
logger.debug("End - step 2 : " + s + " | " + finalJ);
return "step2 output - " + s + " | " + finalJ;
}));
}
}

// Wait for the completion
for (CompletableFuture<?> future : futures) {
future.join();
}
}

关于Java CompletableFuture thenCompose 与几个异步任务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58862207/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com