Skip to main content
1:1 mock interviews with Sumit, scored on a real hiring rubric.Book a slot →
TOPIC 4 OF 5 · 2 MIN READ

CompletableFuture and Async Programming

CompletableFuture lets you compose async steps: run calls in parallel, chain transformations, combine results and handle errors without blocking. It is the standard way to call several services at once in a Java backend.

What you will learn

  • Start async work with supplyAsync and a custom executor
  • Chain with thenApply, thenCompose and thenCombine
  • Wait for many with allOf and anyOf
  • Handle errors and timeouts

Key concepts

thenApply vs thenCompose

thenApply maps a result to a value (like map). thenCompose maps it to another CompletableFuture and flattens it (like flatMap), for dependent async calls.

thenCombine

Combines two independent futures when both finish: price.thenCombine(stock, Product::new).

Error handling

exceptionally(fn) recovers from an error, handle((v, ex) -> ...) sees both, whenComplete observes without changing the result. orTimeout and completeOnTimeout add deadlines (Java 9+).

Executor

Without one, async methods use the common ForkJoinPool, which is sized for CPU work. Pass your own executor (or a virtual-thread executor) for blocking I/O.

Step by step

Aggregating a product page from three services

CompletableFuture<Product> product = CompletableFuture.supplyAsync(() -> catalog.get(id), ioPool);
CompletableFuture<Price>   price   = CompletableFuture.supplyAsync(() -> pricing.get(id), ioPool)
        .completeOnTimeout(Price.unavailable(), 300, TimeUnit.MILLISECONDS);
CompletableFuture<List<Review>> reviews = CompletableFuture.supplyAsync(() -> reviewsApi.top(id), ioPool)
        .exceptionally(ex -> List.of());   // reviews are optional

ProductPage page = CompletableFuture.allOf(product, price, reviews)
        .thenApply(v -> new ProductPage(product.join(), price.join(), reviews.join()))
        .get(1, TimeUnit.SECONDS);

Examples

Dependent calls with thenCompose

CompletableFuture<Invoice> invoice = findUser(id)                  // CF<User>
        .thenCompose(user -> findLatestOrder(user))                // CF<Order>
        .thenCompose(order -> billing.createInvoice(order))         // CF<Invoice>
        .whenComplete((inv, ex) -> { if (ex != null) log.warn("invoice failed", ex); });

Practise it

Try these without looking back. If you can explain each one out loud, you are ready for this question.

  • Call 5 flight-price APIs in parallel and return the cheapest that answers within 2 seconds.
  • Explain the difference between join() and get().

Interview questions

What interviewers ask next on this topic. Answer out loud first, then open the model answer.

Future vs CompletableFuture?

Future only lets you block with get or cancel. CompletableFuture can be completed manually and composed with callbacks (thenApply, thenCombine, allOf) and error handlers, without blocking a thread to wait.

thenApply vs thenApplyAsync?

thenApply runs the function on whichever thread completed the previous stage (or the caller if already done). thenApplyAsync submits it to an executor (the common pool by default, or the one you pass).

Summary

Compose async work with supplyAsync on a suitable executor, thenApply/thenCompose/thenCombine for chaining, allOf for fan-out, and exceptionally, handle and timeouts for resilience.

Stuck on this one? Talk to Sumit.

Keys: F focus mode · ← → previous / next topic · Esc leave focus