skip to content

Transforming & Chaining

thenApply maps a value, thenAccept consumes it, thenRun ignores it, and thenCompose flattens a stage that itself returns a future. The thenApply versus thenCompose question is the map-versus-flatMap of the async world and comes up constantly.

part ofJavaread it →
on this pageshow

questions

5

What does thenApply do on a CompletableFuture, and how does it differ from thenAccept and thenRun?

level: juniorimportance: must knowfreq 70%

answer

  1. Apply = Function (map), Accept = Consumer (side effect), Run = Runnable (ignore result)
  2. Apply returns CF<R>; Accept/Run return CF<Void>
  3. Runs only on SUCCESS; exception skips them
  4. non-Async: completing or calling thread; Async: a pool

basics

~10 s

thenApply transforms the result into a new value (map). thenAccept consumes the result but returns nothing. thenRun runs an action that ignores the result entirely. All three run only when the stage completes normally.

solid answer

~50 s

All three register a callback that runs once the upstream CompletableFuture completes successfully. They differ by what the callback receives and returns. thenApply takes a Function<T,R>: it receives the result and returns a transformed value, producing a CompletableFuture<R> — it maps a value. thenAccept takes a Consumer<T>: it receives the result, does a side effect, and returns CompletableFuture<Void>. thenRun takes a Runnable: it ignores the result completely and returns CompletableFuture<Void> — useful for fire-and-forget completion actions like logging or cleanup. The plain versions promise no particular thread: the callback usually runs on the thread that completed the stage, or on the caller's thread if the stage is already complete; the thenXxxAsync variants hand it to the common ForkJoinPool or a supplied executor. If the upstream completed exceptionally, none of them run — the exception propagates downstream.

go deeper

for a junior

Knows thenApply maps the value, thenAccept consumes it, thenRun ignores it, and can match each to Function/Consumer/Runnable.

for a middle

Adds the return types (CF<R> vs CF<Void>) and that they fire only on success, with the exception skipping them.

for a senior

Explains threading (completing thread vs Async/ForkJoinPool) and why the three functional interfaces exist; picks the right one by intent.

for a principal

Discusses executor selection, thread-confinement and back-pressure implications of where callbacks run, and sets team conventions (always-Async with an explicit pool) for predictability.

## Background: what a CompletableFuture is A **CompletableFuture<T>** (from `java.util.concurrent`) represents a value of type `T` that may not exist yet — it is a *promise* of a future result. A *stage* is one CompletableFuture in a pipeline. When the computation finishes, the future is **completed**, either *normally* (with a value) or *exceptionally* (with a Throwable). You don't block and ask 'is it done?'; instead you **register callbacks** that the runtime invokes automatically when completion happens. This is the foundation of asynchronous, non-blocking code. ## The three single-dependency transforms These methods all attach exactly one callback to one upstream stage. They differ only in the **functional interface** the callback uses, which controls what it sees and what the new stage holds: | Method | Callback type | Receives result? | Returns a value? | New stage type | |---|---|---|---|---| | `thenApply` | `Function<T,R>` | yes | yes (`R`) | `CompletableFuture<R>` | | `thenAccept` | `Consumer<T>` | yes | no | `CompletableFuture<Void>` | | `thenRun` | `Runnable` | no | no | `CompletableFuture<Void>` | - **thenApply** is a **map**: 'when the value arrives, transform it into another value.' Example: a `CompletableFuture<String>` holding a JSON body → `thenApply(this::parse)` → `CompletableFuture<User>`. - **thenAccept** is a **terminal consumer with a result**: 'when the value arrives, do something with it' (write to DB, send to socket). It returns `CompletableFuture<Void>` so you can still chain *completion* actions, but downstream stages can't see the value. - **thenRun** **ignores the value**: 'when the previous step finishes, run this.' Its callback takes no arguments — good for cleanup, releasing a latch, or logging 'done'. ## When does the callback run, and on which thread? - It runs **only after successful completion** of the upstream stage. If the upstream finished *exceptionally*, the callback is **skipped** and the exception flows straight downstream (you'd handle it with `exceptionally`/`handle`). - **Thread:** the non-`Async` versions promise no particular thread. The `CompletableFuture` Javadoc says such an action "may be performed by the thread that completes the current CompletableFuture, or by any other caller of a completion method". In practice that is usually the thread that *completed* the upstream stage, and in OpenJDK, if the stage was *already* complete when you call `thenApply`, the function runs **synchronously on your calling thread** before `thenApply` returns. The `thenApplyAsync` / `thenAcceptAsync` / `thenRunAsync` variants run it on the **common ForkJoinPool** (or an `Executor` you pass), which matters for blocking work or thread-confined resources. ## Why three methods instead of one Java's type system has no single 'callback' type — it has specialized functional interfaces. `Function` returns a value, `Consumer` does not, `Runnable` takes none. The three names map cleanly onto those, giving you precise, self-documenting intent and the correct return type without casting or `null` returns.

  • If the upstream stage completes exceptionally, does thenApply's function run?
    No. thenApply (and thenAccept/thenRun) only fire on normal completion. On exceptional completion the function is skipped and the exception propagates to the next stage, where exceptionally/handle/whenComplete can deal with it.
  • Which thread runs the thenApply callback?
    Usually the thread that completed the upstream stage, or your calling thread if the stage is already complete; the Javadoc only says it may be the completing thread or any other caller of a completion method. Use thenApplyAsync to hand it to the common ForkJoinPool or a supplied Executor instead.

  • Saying thenAccept or thenRun returns the original value — both return CompletableFuture<Void>.
  • Thinking thenRun receives the result — it takes a Runnable and gets nothing.
  • Assuming the callback always runs on a background thread — non-Async variants may run on the caller's thread.
  • Believing thenApply still runs after an upstream exception.

CompletableFuture and CompletionStage
Java 1.8

context

open as a page

In Java's CompletableFuture API, what is the difference between thenApply and thenCompose, and when must you use thenCompose?

level: middleimportance: must knowfreq 85%

basics

~10 s

Use thenApply when your function returns a plain value. Use thenCompose when your function itself returns another CompletableFuture, so you chain asynchronous steps without ending up with a CompletableFuture wrapped inside a CompletableFuture.

open as a page

How do exceptions flow through a chain of CompletableFuture thenApply/thenCompose stages, and how is that hidden by the returned types?

level: seniorimportance: must knowfreq 65%

basics

~10 s

If any stage throws or its upstream failed, that stage completes exceptionally and every following thenApply/thenCompose is skipped — the error 'short-circuits' to the end. You handle it with exceptionally, handle, or whenComplete.

open as a page

What do CompletableFuture's *Async variants (thenApplyAsync, etc.) change, and why does supplying your own Executor matter?

level: seniorimportance: should knowfreq 60%

basics

~20 s

The Async variants hand the callback to an executor instead of running it inline on the completing or calling thread. Without an Executor they use the shared common ForkJoinPool; passing your own pool keeps blocking work off that shared pool.

open as a page

How would you design a clean, composable async pipeline with CompletableFuture transforms, and what pitfalls do you guard against at scale?

level: principalimportance: should knowfreq 35%

basics

~20 s

Build pipelines from small, pure transform steps: thenApply for mapping, thenCompose for chaining async calls, and explicit executors for blocking work. Always attach error handling, avoid nested futures, and never block inside a callback on a shared pool.

open as a page