Java 从CompletableFuture.allOf丢失了一些请求
问题是我必须逐个调用API,所以我使用CompletableFunction,如下所示Java 从CompletableFuture.allOf丢失了一些请求,java,spring-boot,asynchronous,completable-future,Java,Spring Boot,Asynchronous,Completable Future,问题是我必须逐个调用API,所以我使用CompletableFunction,如下所示 List<CompletableFuture<Void>> completableFutures = new ArrayList<>(); List<Bclass> listAll = new ArrayList<>(); for (SthClass e : result) { CompletableFuture<Void> fut
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();
List completableFutures=new ArrayList();
List listAll=new ArrayList();
对于(SthClass e:结果){
CompletableFuture=CompletableFuture.SupplySync(()->fundInService.doRetryTransaction(retryTransactionRequestDto),threadConfiguration.getAsyncExecutor()
.然后接受((结果)->{
Aclass a=新Aclass();
增加(a);
});
completableFutures.add(未来);
}
CompletableFuture allFutures=CompletableFuture.allOf(completableFutures.toArray(新的completableFutures[0]);
all futures.get();
我从allFutures得到了一个随机大小的listAll
我不知道这段代码发生了什么,Java新手使用
synchronizedList
而不是ArrayList
,因为ArrayList
不是线程安全的
List<Bclass> listAll = Collections.synchronizedList( new ArrayList() );
List listAll=Collections.synchronizedList(新的ArrayList());
您能详细说明您的期望值和得到的结果吗?不要操纵可能由不同线程执行的操作列表。作业完成后收集结果值列表。就像在。这是因为你不等待。当listAll是completed@janardhansharma我希望得到listAll
包含10个列表,但我随机得到它。@Holger似乎是对的,但让我试试,谢谢分享