丢失了来自 CompletableFuture.allOf 的一些请求

问题描述 投票:0回答:2

问题是我必须一一调用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 新手

java spring-boot asynchronous completable-future
2个回答
0
投票

使用

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

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

0
投票

上面 divilipir 的回答对我有用!非常感谢!

© www.soinside.com 2019 - 2024. All rights reserved.