Home > OS >  How to use CompletableFuture to execute the threads parallaly without waiting and combine the result
How to use CompletableFuture to execute the threads parallaly without waiting and combine the result

Time:12-05

I have executeGetCapability method which is executed in different threads but these threads runs sequentially..meaning one is completed after the other

    @Async("threadPoolCapabilitiesExecutor")
    public CompletableFuture<CapabilityDTO>  executeGetCapability(final String id, final LoggingContextData data){...}

and this method is called in following way:

public CapabilityResponseDTO getCapabilities(final List<String> ids) {
    final CapabilityResponseDTO responseDTO = new CapabilityResponseDTO();
    final List<CapabilityDTO> listOfCapabilityDTOS = new ArrayList<>();
    try {
        for (String id: ids) {
            listOfCapabilityDTOS .add(
                    asyncProcessService.executeGetCapability(id, LoggingContext.getLoggingContextData()).get());
        }
    } catch (Exception e) {
        ....
    }
    responseDTO.setDTOS(listOfCapabilityDTOS );
    return responseDTO;
}

How can i call executeGetCapability method using CompletableFuture so that thread runs in parallel without waiting for each other and then the result is combined ?? how can i use here CompletableFuture.supplyAsync and or .allOf methods ? Can someone explain me

Thanks

CodePudding user response:

The reduce helper function from this answer converts a CompletableFuture<Stream<T>> to a Stream<CompletableFuture<T>>. You can use it to asynchronously combine the results for multiple calls to executeGetCapability:

// For each id create a future to asynchronously execute executeGetCapability
Stream<CompletableFuture<CapabilityDTO>> futures = ids.stream()
    .map(id -> executeGetCapability(id, LoggingContext.getLoggingContextData()));

// Reduce the stream of futures to a future for a stream 
// and convert the stream to list
CompletableFuture<List<CapabilityDTO>> capabilitiesFuture = reduce(futures)
    .thenApply(Stream::toList);

responseDTO.setDTOS(capabilitiesFuture.get());

CodePudding user response:

This post was really helpful and answered my question. https://dzone.com/articles/java-8-parallel-processing-with-completable-future

  • Related