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;
}
CodePudding user response:
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 CompletableFuture
s instead and then CompletableFuture.allOf()
but for something this simple what you have works fine. See also Waiting on a list of Future
CodePudding user response:
Your code will block until the processFuture
is finished, then it will block until the taskFuture
is finished.
The callables will be processed in parallel, so here you are saving time (assuming thread pool size >= 2).