简体   繁体   中英

Asynchronous api call using CompletableFuture in Java 8

Following is my use case that I am trying to implement using CompletableFuture class

  1. I have a list of ids for which I want to do an api call for each of the ids
  2. I want to get the response back from the api calls and save it in a list or map for further processing
  3. I also do not want to wait till I get the responses of all api calls. I want to set a time limit and get whatever data is available till that time.

I tried the following code but it is not working correctly

// list content
List<Integer> ids = Arrays.asList(1,2,3,4,5);


// Api call using parallel stream - not sure how I can include a time limit here so that
// I can get partial list of updatedIds based on delay settings
List<Integer> updatedIds  = ids.parallelStream().map(item -> {
            // api call equivalent of increment 1
            return item+1;
        }).collect(Collectors.toList());



// Asynchronous api call using CompletableFuture class - not sure how I can
// dynamically call the function for all items in the ids list.
// Following is what I tried to do by reading 
// https://www.baeldung.com/java-completablefuture
encounterIdSet.parallelStream().forEach(id -> {
     CompletableFuture<Integer> completableFuture = CompletableFuture.supplyAsync(() -> serviceCall(id));
});
List<Integer> = completableFuture.get(60, TimeUnit.SECONDS); // may be in incorrect location 



// I want to process the list of returned integers here - whatever I am getting in 60 seconds timeout mentioned in timeout settings



// service call definition 
Integer serviceCall(id){
  return id +1;
}

Can you please guide me on this use case? I need 1. timeout settings with 2. asynchronous data processing of 3. unknown number of items.

I am using Java 8.

Thanks.

I can think of two ways, with some minor differences:

    List<CompletableFuture<Integer>> futures = ids.stream()
            .map(id -> CompletableFuture.supplyAsync(() -> id + 1))
            .collect(Collectors.toList());
    try {
        CompletableFuture.allOf(futures.toArray(new CompletableFuture[0])).get(60, TimeUnit.SECONDS);
    } catch (InterruptedException | ExecutionException | TimeoutException e) {
        // log
    }
    List<Integer> result = futures
            .stream()
            .filter(future -> future.isDone() && !future.isCompletedExceptionally())
            .map(CompletableFuture::join)
            .collect(Collectors.toList());   

or

     List<Integer> result = ids.stream()
            .map(id -> CompletableFuture.supplyAsync(() -> id + 1))
            .map(cf -> {
                    try {
                        return cf.get(60, TimeUnit.SECONDS);
                    } catch (InterruptedException | ExecutionException | TimeoutException e) {
                        // log
                    }
                    return null;
            })
            .filter(Objects::nonNull)
            .collect(Collectors.toList());

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