How to make parallel calls in Java with CompletableFuture example

By Adrian Matei

Some time ago I wrote how elegant and rapid is to make parallel calls in NodeJS with async-await and Promise.all
Well, it turns out in Java is just as elegant and succinct with the help of CompletableFuture
which was introduced in Java 8. To demonstrate that let’s imagine that we need to retrieve ToDos from a REST service, given their Ids. Of course
we could iterate through the list of Ids and sequentially call the web service, but it’s much more performant to do it in parallel
with asynchronous calls.

Here is the piece of code that might do just that:

import org.codingpedia.example;

import javax.inject.Inject;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.function.Supplier;

public class ParallelCallsDemoService {

    RestApiClient restApiClient;

    public List<ToDo> getToDos(List<String> ids){

        List<CompletableFuture<ToDo>> futures =
                          .map(id -> getToDoAsync(id))

        List<ToDo> result =

        return result;

    CompletableFuture<ToDo> getToDoAsync(String id){

        CompletableFuture<ToDo> future = CompletableFuture.supplyAsync(new Supplier<ToDo>() {
            public ToDo get() {
                final ToDo toDo = restApiClient.getToDo(id);

                return toDo;

        return future;



  • the supplyAsync method takes a Supplier
    which contains the code we want to execute asynchronously – in our case this is where the REST call takes placeā€¦
  • we fire all the rest calls and we collect all the futures in a list
  • in the end we collect all the results with the help of the join() method – this returns the value of the CompletableFuture
    when complete, or throws an (unchecked) exception if completed exceptionally.

How to make parallel calls in Java with CompletableFuture example was originally published by Codingpedia Association at CodingpediaOrg on January 26, 2018.