꺼내먹어요

CompletableFuture - http 호출 병렬처리

양승길 2023. 4. 20. 19:35
List<CompletableFuture<Response>> futures = new ArrayList<>();
List<Response> accountKeys = Lists.newArrayList();

for(int i = 1 ; i <= returnAccounts.size() ; i++){
    final int idx = i;
    CompletableFuture<Response> future = CompletableFuture.supplyAsync(() -> httpCall());
    futures.add(future);
    if(i % 20 == 0){
        CompletableFuture.allOf(futures.toArray(new CompletableFuture[0])).join();
        accountKeys.addAll(futures.stream().map(CompletableFuture::join).collect(Collectors.toList()));
        futures = new ArrayList<>();
    }
}

if(!futures.isEmpty()){
	CompletableFuture.allOf(futures.toArray(new CompletableFuture[0])).join();
	accountKeys.addAll(futures.stream().map(CompletableFuture::join).collect(Collectors.toList()));
}

System.out.println(accountKeys);