Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Java Concurrency: Need to make 2 webservice calls simultaneously – is this correct?

I want to make web calls to 2 different services simultaneously. At the end, I zip the 2 Response objects into one stream. I’m using a Callable, but I’m not sure I’m going about this in the correct way. It seems as though I’m still going to be blocked by the first get() call to the Future, right? Can someone tell me if I’m on the right track? This is what I have so far:

// submit the 2 calls to the thread pool
ExecutorService executorService = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
Future<Mono<Response<ProcessInstance>>> processFuture =
        executorService.submit(() -> getProcessInstances(processDefinitionKey, encryptedIacToken));
Future<Mono<Response<Task>>> taskFuture =
        executorService.submit(() -> getTaskResponses(processDefinitionKey, encryptedIacToken, 100, 0));

// get the result of the 2 calls
Optional<Tuple2<Response<ProcessInstance>, Response<Task>>> tuple;
try {
    Mono<Response<ProcessInstance>> processInstances = processFuture.get();
    Mono<Response<Task>> userTasks = taskFuture.get();
    tuple = processInstances.zipWith(userTasks).blockOptional();
} catch (InterruptedException e) {
    log.error("Exception while processing response", e);
    // Restore interrupted state...
    Thread.currentThread().interrupt();
    return emptyProcessResponseList;
} catch (ExecutionException e) {
    log.error("Exception while processing response", e);
    return emptyProcessResponseList;
}

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Given: You need to wait until both tasks are complete.

If processFuture ends first, you’ll immediately fall through and wait until taskFuture ends. If taskFuture ends first you’ll block until processFuture ends, but the taskFuture.get() call will return instantly since that task is done. In either case the result is the same.

You could use CompletableFutures instead and then CompletableFuture.allOf() but for something this simple what you have works fine. See also Waiting on a list of Future

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading