简体   繁体   中英

What I'm doing wrong with CompletableFuture that aren't executing in parallel

I have splitted a list in 5 parts, and I want to execute in parallel using restTemplate, I have the following method:

@Async
private CompletableFuture<List<Cidade>> MontarCidadesPorEstado(List<Cidade> listaCidades, List<UF> estado) {

    estado.forEach(es -> {
            Map<String, String> param = new HashMap<String, String>();
            param.put("UF", es.getSigla());

            Cidade[] cidades = restTemplate.getForObject(url, Cidade[].class, param);

            listaCidades.addAll(Arrays.asList(cidades));
     });

    return CompletableFuture.completedFuture(listaCidades);
}

So created a List of CompletableFuture to execute all of them in parallel, but when an add each CompletableFuture into a list it's already execute it without make it parallel, ex:

     List<List<UF>> subSets = Lists.partition(estados, 5);
     List<CompletableFuture<List<Cidade>>> lstCompletableFuture = new ArrayList();

     subSets.forEach(estado -> {
         lstCompletableFuture.add(MontarCidadesPorEstado(listaCidades, estado));
     });

     CompletableFuture.allOf(lstCompletableFuture.toArray(new CompletableFuture[lstCompletableFuture.size()]));

What I'm doing wrong, I thought it's supposed to execute the method MontarCidadesPorEstado when I call CompletableFuture.allOf .

I assume that MontarCidadesPorEstado is a local method call.

Therefore the call is local it doesn't go through a proxy and is not asynchronous.

You have define the MontarCidadesPorEstado method in another bean and then call this bean.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM