Quiz: CompletableFuture in Java: Chaining Asynchronous Tasks

Total: 8 questions

1. 

What is CompletableFuture and how is it different from Future?

CompletableFuture is a class in java.util.concurrent (Java 8) that implements both Future and CompletionStage. It is a Future you can complete by hand and attach continuations to, instead of blocking in get().

A plain Future from an ExecutorService can only hand over its result through the blocking get(). CompletableFuture adds what Future lacks:

  • continuations when the result is ready: thenApply, thenAccept, thenRun, thenCompose;
  • combining tasks: thenCombine, allOf, anyOf;
  • manual completion: complete(value), completeExceptionally(ex);
  • error handling inside the chain: exceptionally, handle, whenComplete;
  • a timeout on the result itself: orTimeout, completeOnTimeout (Java 9);
  • non-blocking reads: getNow(default).

There is also a difference the other way round: cancel(true) on the Future from submit() interrupts the task thread, while on a CompletableFuture it only marks the future as cancelled and the task keeps running.

2. 

What is the difference between supplyAsync() and runAsync(), which pool do they run in, and when should you pass your own Executor?

supplyAsync(Supplier<T>) starts a task that returns a value and gives back a CompletableFuture<T>; runAsync(Runnable) starts a task without a value, CompletableFuture<Void>. Both return immediately.

Without a second argument the task runs in ForkJoinPool.commonPool(). Its threads are daemons, so if main ends without join(), the JVM exits and the task is silently lost. If the parallelism of commonPool is below two (a machine or container with 1-2 CPUs), CompletableFuture creates a new thread for each task instead.

Pass your own Executor as the second argument when the task blocks: reads files, calls a database or the network. commonPool has as many threads as cores minus one and is shared by the whole JVM: parallel streams and every *Async method without its own pool use it too.

try (ExecutorService io = Executors.newFixedThreadPool(10)) {
    CompletableFuture<String> page = CompletableFuture.supplyAsync(() -> download(url), io);
    System.out.println(page.join().length());
}

You close your own pool yourself; CompletableFuture will not do it. Supplier cannot throw checked exceptions, so an IOException inside the task is usually wrapped in an UncheckedIOException.

3. 

What is the difference between join() and get() in CompletableFuture, and what are getNow() and complete() for?

Both methods block the thread until the result is ready. The difference is in the exceptions:

  • join() throws the unchecked CompletionException (the original error is in getCause()), so it can be called inside lambdas and streams: futures.stream().map(CompletableFuture::join);
  • get() throws the checked ExecutionException and InterruptedException, like a plain Future, and they must be caught or declared.

After cancellation both throw CancellationException.

getNow(valueIfAbsent) does not wait: it returns the result if it is ready, otherwise the given value. complete(value) completes the future by hand and returns true; if the future is already complete, it returns false and the value does not change. A new CompletableFuture<>() plus complete()/completeExceptionally() turns a callback API into a future without any pool. The static completedFuture(value) and failedFuture(ex) (Java 9) create an already completed future.

4. 

What is the difference between thenApply, thenCompose and thenCombine in CompletableFuture?

  • thenApply(fn) transforms the result with a function T -> U, like map on streams.
  • thenCompose(fn) takes a function T -> CompletionStage<U> that itself starts the next async operation depending on the result; the nesting is flattened, like flatMap. Example: load a user, then load the orders of that user.
  • thenCombine(other, fn) combines the results of two independent futures with a function (T, U) -> V; both tasks run in parallel.
CompletableFuture<Double> total = loadUser(42)
        .thenCompose(OrderTotalExample::loadOrders)
        .thenApply(orders -> orders.stream().mapToDouble(Order::amountUsd).sum())
        .thenCombine(loadUsdRate(), (usd, rate) -> usd * rate);

Use thenApply instead of thenCompose on the first line, and you get CompletableFuture<CompletableFuture<List<Order>>>. The rule: if the function returns a plain value, use thenApply; if it returns a CompletionStage, use thenCompose.

Each method has an Async variant. A stage without Async runs in the thread that completed the previous stage, or right away in the calling thread if that stage is already done; thenApplyAsync always sends the function to commonPool or to the given Executor.

5. 

How do CompletableFuture.allOf() and anyOf() work, and how do you collect the results of all tasks?

allOf(cfs...) returns a CompletableFuture<Void> that completes when all the given futures have completed. It does not collect their results; you take them with join() on each future, which by then is already done:

CompletableFuture<Void> all = CompletableFuture.allOf(requests.toArray(new CompletableFuture[0]));
List<Price> prices = all
        .thenApply(v -> requests.stream().map(CompletableFuture::join).toList())
        .join();

If at least one task fails, allOf completes exceptionally too, but only after all the others have finished. To keep the successful results, handle the error in each future before allOf, for example f.handle((v, ex) -> ex == null ? v : null).

anyOf(cfs...) completes together with the first future to complete and returns a CompletableFuture<Object>, so a cast is needed. It does not cancel the other tasks; they keep running. For two futures the type-safe alternative is applyToEither.

6. 

What is the difference between exceptionally(), handle() and whenComplete() in CompletableFuture?

An exception in a stage is not thrown out; it is stored in the future and passed down the chain: the following thenApply/thenAccept stages are skipped until a handler is reached.

  • exceptionally(ex -> value) is called only on failure and replaces the error with a fallback value; on success the result passes through unchanged.
  • handle((value, ex) -> newValue) is always called, receives both the result and the exception (ex == null on success) and returns a new value, possibly of another type.
  • whenComplete((value, ex) -> ...) is always called but does not change the result: the future completes with the same value or the same error. Good for logs and metrics.
  • exceptionallyCompose (Java 12) starts another async stage on failure, for example a call to a backup service.

Which object reaches the handler: an exception from supplyAsync or any stage is wrapped in a CompletionException, while a handler attached to a future completed with completeExceptionally() receives the original exception. That is why the cause is unwrapped before instanceof: ex instanceof CompletionException ? ex.getCause() : ex.

7. 

How do you set a timeout on a CompletableFuture, and does cancel(true) interrupt a running task?

Since Java 9 the timeout is set on the future itself:

  • orTimeout(timeout, unit): if the result is not ready in time, the future completes with a TimeoutException (through join() it arrives inside a CompletionException);
  • completeOnTimeout(value, timeout, unit): the future completes with a fallback value.
String answer = CompletableFuture.supplyAsync(() -> slowService(2_000), pool)
        .completeOnTimeout("cached value", 500, TimeUnit.MILLISECONDS)
        .join();

Both methods modify and return the same future, but neither stops the task: it runs to the end and holds a pool thread the whole time.

cancel(true) does not interrupt a running task either: in CompletableFuture the mayInterruptIfRunning parameter has no effect. The future completes with a CancellationException (join() throws it, dependent stages get a CompletionException with it inside), while the task runs to the end and its result is thrown away. If the work really has to stop, the task must check a flag itself, for example isCancelled() or your own AtomicBoolean.

8. 

What are the most common mistakes when working with CompletableFuture?

Most of them produce neither an exception nor a compiler warning:

  • No join() at the end of main or a test: the task in commonPool never gets to run, because daemon threads do not keep the JVM alive.
  • Blocking I/O in supplyAsync without your own pool: commonPool threads are busy waiting, and parallel streams and other async tasks stall. The fix is your own Executor as the second argument.
  • thenApply instead of thenCompose: the type becomes CompletableFuture<CompletableFuture<T>>.
  • A chain with no handler and no join(): the exception sits in a future nobody reads. Put exceptionally or whenComplete with logging as the last stage.
  • join() inside a stage that waits for a task of the same bounded pool: the pool threads wait for each other and the program hangs. Link tasks with thenCompose/thenCombine instead.
  • supplyAsync(task).join() on the very next line, for example in a loop: the requests run strictly one after another. Start all independent tasks first and wait once at the end.
Page 1 of 1