首页 > 解决方案 > 丢失了来自 CompletableFuture.allOf 的一些请求

问题描述

问题是我必须一个一个地调用一个 API,所以我使用 CompleableFunction 如下

List<CompletableFuture<Void>> completableFutures = new ArrayList<>();
List<Bclass> listAll = new ArrayList<>();

for (SthClass e : result) {
  CompletableFuture<Void> future = CompletableFuture.supplyAsync(() -> fundInService.doRetryTransaction(retryTransactionRequestDto), threadConfiguration.getAsyncExecutor())
                            .thenAccept((result) -> {
                                Aclass a = new Aclass();

                                listAll.add(a);
                            });
  completableFutures.add(future);
}

CompletableFuture<Void> allFutures = CompletableFuture.allOf(completableFutures.toArray(new CompletableFuture[0]));
allFutures.get();

我从 allFutures 获得了随机大小的 listAll

我不知道这段代码发生了什么,Java 新手

标签: javaspring-bootasynchronouscompletable-future

解决方案


使用synchronizedList代替ArrayList,因为ArrayList不是线程安全的

List<Bclass> listAll = Collections.synchronizedList( new ArrayList() );

推荐阅读