Sub topic 4
Transforming results with thenApply and thenAccept
This chapter assumes you know Java 8 lambdas and method references, the functional interfaces Function, Consumer, and Runnable, and how to create a CompletableFuture with supplyAsync. It covers how to attach work to a future's result without blocking a thread.
The idea: a pipeline of stages
Each CompletableFuture is a stage. When you call a then... method on a stage, you get a new stage back. The new stage runs when the previous one completes normally. If the previous stage fails, the new stage does not run its function. It completes with the same failure instead.
The methods in this chapter are:
| Method | Function type | Input | Returns | Use it to |
|---|---|---|---|---|
| `thenApply` | `Function<T, U>` | the result | `CompletableFuture<U>` | convert a result into another value |
| `thenAccept` | `Consumer<T>` | the result | `CompletableFuture<Void>` | use a result for a side effect |
| `thenRun` | `Runnable` | nothing | `CompletableFuture<Void>` | run an action after completion |
thenApply: map the result
thenApply is the asynchronous counterpart of Stream.map or Optional.map. It takes the result, applies a function, and gives you a future of the new value.
import java.util.concurrent.CompletableFuture;
public class Basics {
public static void main(String[] args) {
CompletableFuture<String> future = CompletableFuture
.supplyAsync(() -> "hello")
.thenApply(String::toUpperCase);
System.out.println(future.join());
}
}This prints HELLO. The supplyAsync call starts the work on the common pool. The thenApply call returns immediately, because it only registers a function to run later.
The result type can change at each step. You can chain several steps, and each one sees the output of the one before it:
import java.util.concurrent.CompletableFuture;
public class Chain {
public static void main(String[] args) {
CompletableFuture<Integer> length = CompletableFuture
.supplyAsync(() -> " concurrency ")
.thenApply(String::trim)
.thenApply(String::length);
System.out.println(length.join());
}
}This prints 11. The types move from CompletableFuture<String> to CompletableFuture<Integer>.
thenAccept: consume the result
Use thenAccept at the end of a pipeline, where you do something with the value but produce nothing new. Typical uses are logging, writing to a response, or updating a UI.
import java.util.concurrent.CompletableFuture;
public class Accept {
public static void main(String[] args) {
CompletableFuture<Void> done = CompletableFuture
.supplyAsync(() -> 21)
.thenApply(n -> n * 2)
.thenAccept(n -> System.out.println("answer = " + n));
done.join();
}
}This prints answer = 42. The returned CompletableFuture<Void> has no value, but it still tells you when the work finished and whether it failed. Keep a reference to it if you need to wait for the side effect. In a short program like this one, join() also stops main from exiting before the common pool's daemon threads finish.
thenRun: ignore the result
thenRun takes a Runnable, so it cannot see the result. It is useful for cleanup or notifications that do not depend on the value.
import java.util.concurrent.CompletableFuture;
public class Run {
public static void main(String[] args) {
CompletableFuture
.supplyAsync(() -> "report")
.thenRun(() -> System.out.println("step finished"))
.join();
}
}This prints step finished. Like thenAccept, it returns CompletableFuture<Void>.
Which thread runs your function?
The thread that runs a dependent function depends on timing:
- If the source stage is still running when you register the function, the thread that completes the source runs your function right after it finishes.
- If the source stage has already completed when you register the function, the thread that calls
thenApplyruns it immediately, inside that call.
This matters. A function registered on an already-completed future runs on the caller's thread, so a slow function can block the caller. The next code shows it:
import java.util.concurrent.CompletableFuture;
public class WhichThread {
public static void main(String[] args) {
CompletableFuture<String> ready = CompletableFuture.completedFuture("x");
ready.thenApply(s -> {
System.out.println("running on " + Thread.currentThread().getName());
return s;
}).join();
}
}This prints running on main, because the future was already complete. The Async variants such as thenApplyAsync always submit the function to an executor. Chapter 10 covers them in detail. For now, remember that plain thenApply gives no guarantee about the thread.
Fast functions only
Because a plain thenApply function may run on the thread that completed the previous stage, keep these functions short and non-blocking. If a function does slow work, such as a database call, you hold up whichever thread happens to run it. That thread could be a pool worker doing other tasks, or your own caller.
A rule of thumb:
- Pure computation on the result, such as parsing, formatting, or mapping fields:
thenApplyis fine. - A function that itself returns a
CompletableFuture: usethenCompose(the next chapter), notthenApply. - Slow blocking work: submit it as its own asynchronous stage with a suitable executor.
The nested future mistake
If you pass a function that returns a future to thenApply, you get a future of a future:
import java.util.concurrent.CompletableFuture;
public class Nested {
static CompletableFuture<Integer> lookup(String key) {
return CompletableFuture.supplyAsync(key::length);
}
public static void main(String[] args) {
CompletableFuture<CompletableFuture<Integer>> nested = CompletableFuture
.supplyAsync(() -> "key")
.thenApply(Nested::lookup);
Integer value = nested.join().join();
System.out.println(value);
}
}This prints 3, but it needs two join calls, and the type is awkward. It compiles and works, which is why people write it by accident. The fix is thenCompose, which flattens the result. The next chapter covers it.
Failures skip the function
When a stage fails, thenApply and thenAccept do not run their functions. The failure moves down the chain to the next stage. Here is an example:
import java.util.concurrent.CompletableFuture;
public class Skipped {
public static void main(String[] args) {
CompletableFuture<Integer> f = CompletableFuture
.<Integer>supplyAsync(() -> {
throw new IllegalStateException("boom");
})
.thenApply(n -> {
System.out.println("never printed");
return n + 1;
});
try {
f.join();
} catch (Exception e) {
System.out.println(e.getClass().getSimpleName());
System.out.println(e.getCause().getMessage());
}
}
}This prints CompletionException and then boom. The lambda inside thenApply never runs. The exception thrown by the source arrives wrapped in a CompletionException, and join rethrows it. The error handling chapter covers exceptionally, handle, and whenComplete.
If your own function throws, the returned stage completes exceptionally and the same wrapping applies to downstream stages and to join:
import java.util.concurrent.CompletableFuture;
public class Throwing {
public static void main(String[] args) {
CompletableFuture<Integer> f = CompletableFuture
.supplyAsync(() -> "abc")
.thenApply(Integer::parseInt);
try {
f.join();
} catch (RuntimeException e) {
System.out.println(e.getCause());
}
}
}This prints java.lang.NumberFormatException: For input string: "abc".
Null results
thenApply allows null as a result. A function can return null, and the next stage receives null. A null reaching thenAccept is passed to the consumer unchanged. This is easy to forget:
import java.util.concurrent.CompletableFuture;
public class Nulls {
public static void main(String[] args) {
CompletableFuture
.supplyAsync(() -> (String) null)
.thenApply(s -> s == null ? "empty" : s.trim())
.thenAccept(System.out::println)
.join();
}
}This prints empty. Without the null check, s.trim() would throw a NullPointerException inside the stage, and the failure would travel down the chain as a CompletionException.
thenApply does not change the original
Each then... call returns a new stage and leaves the source stage alone. You can attach several independent branches to one source:
import java.util.concurrent.CompletableFuture;
public class Branches {
public static void main(String[] args) {
CompletableFuture<String> source = CompletableFuture.supplyAsync(() -> "data");
CompletableFuture<Integer> size = source.thenApply(String::length);
CompletableFuture<String> upper = source.thenApply(String::toUpperCase);
System.out.println(size.join() + " " + upper.join());
}
}This prints 4 DATA. Both branches read the same result. If the result is a mutable object, both functions see the same instance, so mutating it in one branch can affect the other. Prefer immutable values, or copy before you change them.
A common bug comes from dropping the returned stage:
import java.util.concurrent.CompletableFuture;
public class Dropped {
public static void main(String[] args) {
CompletableFuture<String> f = CompletableFuture.supplyAsync(() -> "a");
f.thenApply(s -> s + "b"); // result discarded
System.out.println(f.join()); // prints a, not ab
}
}This prints a. The new stage holds "ab", but the code never keeps it. The same call also hides failures: an exception inside the dropped stage is never observed.
thenAccept versus thenApply returning null
You might be tempted to use thenApply for side effects and return null. Avoid it. thenAccept states your intent, gives you CompletableFuture<Void>, and prevents a meaningless null from flowing downstream.
| Situation | Prefer |
|---|---|
| Convert a value | `thenApply` |
| Print, log, or store a value | `thenAccept` |
| Run an action that ignores the value | `thenRun` |
| Return value is itself a future | `thenCompose` |
Method references and type inference
Method references work well with thenApply. String::length and Integer::parseInt read cleanly. A lambda that throws, as in the Skipped example, needs an explicit type witness such as CompletableFuture.<Integer>supplyAsync(...). The compiler cannot infer the type from a lambda that has no return statement, only a throw.
Exercise
What does the following code print, and why does the second stage not need a null check on its own? CompletableFuture.supplyAsync(() -> "7").thenApply(Integer::parseInt).thenApply(n -> n * 6).thenAccept(System.out::println).join();
Show answer
It prints 42. The first stage produces the string "7", parseInt turns it into the Integer 7, the next stage multiplies it to 42, and thenAccept prints it. No null check is needed because no stage in the chain returns null, so every function receives a real value.
Exercise
A colleague writes CompletableFuture<Void> f = source.thenApply(v -> { log(v); return null; }); and the code does not compile. Why, and what is the better method to use?
Show answer
thenApply returns CompletableFuture<U> where U is the lambda's return type. Returning null gives U the inferred type Object, not Void, so the assignment to CompletableFuture<Void> fails. The better choice is thenAccept(v -> log(v)), which returns CompletableFuture<Void> and states that the stage only has a side effect.
Exercise
You call future.thenApply(String::trim); on an already-completed future and ignore the return value. Is the trimmed text available from future? What happens if the trim throws?
Show answer
No. thenApply returns a new stage and leaves the original future unchanged, so future still holds the untrimmed text. If trim throws, the exception completes only the discarded new stage, so nobody observes the failure.