Video in progress
How do you use CompletableFuture and a Spring executor to call three services in parallel and combine the results?
You start each call in your own executor with CompletableFuture.supplyAsync, put a limit on each with orTimeout or completeOnTimeout, and combine them with allOf. If you don't pass an executor, the commonPool is used, which is bad for blocking I/O.
📖 Answer
A product page needs the price, the stock and the reviews, each from a separate service, each taking about 200 ms. Sequentially that's 600 ms, in parallel roughly 200 ms.
@Service
class ProductPageService {
private final Executor io; // a ThreadPoolTaskExecutor bean from Spring
// ... constructor
ProductPage load(long id) {
var price = CompletableFuture.supplyAsync(() -> pricing.price(id), io)
.orTimeout(500, TimeUnit.MILLISECONDS);
var stock = CompletableFuture.supplyAsync(() -> inventory.stock(id), io)
.completeOnTimeout(Stock.unknown(), 300, TimeUnit.MILLISECONDS);
var reviews = CompletableFuture.supplyAsync(() -> reviewsClient.top(id), io)
.exceptionally(ex -> List.of()); // the page should open even without reviews
CompletableFuture.allOf(price, stock, reviews).join();
return new ProductPage(price.join(), stock.join(), reviews.join());
}
}
There are three different policies here: a page without a price is meaningless, so a timeout is an error; if the stock is unknown, a default value; the reviews are optional.
Things to watch:
orTimeoutdoesn't stop the HTTP call underneath, it only stops the waiting. The HTTP client must have its own timeout too, otherwise the threads stay tied up;join()wraps the exception inCompletionException, so unwrapgetCause()in the advice;- MDC and SecurityContext don't carry over to the new thread by themselves, so the executor needs a
TaskDecorator; - in Java 21 you can do the same with a virtual thread executor, but the timeout and fallback decisions are still yours.
An @Async method can also return a CompletableFuture, but the timeout and fallback still get written on the caller's side, and the explicit code above is often easier to follow.
Sign up to mark studied questions and save your progress.