Java CompletableFuture然后用几个异步任务进行组合



我有一个由两个异步步骤组成的过程。第二个步骤基于第一个步骤的结果运行。这个过程是循环启动的。挑战在于,第二步是由几个异步任务完成的,这些任务接受第一步迭代的输出。第一步完成后,我想使用第一步的结果启动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();
}
}

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

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

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();
}
}

最新更新