Sub topic 6
Combining independent results with thenCombine
This chapter assumes you know Java 8 lambdas, Function and Supplier, and the basics of supplyAsync and thenApply. You should also know that join waits for a result. Here you learn to merge the results of two futures that do not depend on each other.
Dependent versus independent work
thenCompose fits when step B needs the value from step A. For example, you look up a user ID, and then you fetch that user's orders. The second call cannot start until the first finishes.
Sometimes two pieces of work have no such link. You might need a customer's name and the current price of a product. Neither call needs the other's answer. You can start both at once and merge the two values when both are ready. thenCombine does this:
<U, V> CompletableFuture<V> thenCombine(
CompletionStage<? extends U> other,
BiFunction<? super T, ? super U, ? extends V> fn)It is called on one future (this, of type T). It takes a second future (other, of type U) and a BiFunction. When both futures have completed normally, it calls the function with both values. The returned future holds the function's result.
A first example
The helper below sleeps to simulate a slow call. Both futures are created before either is combined, so they run at the same time.
import java.util.concurrent.CompletableFuture;
public class CombineBasics {
static void pause(long millis) {
try {
Thread.sleep(millis);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
public static void main(String[] args) {
long start = System.nanoTime();
CompletableFuture<String> name = CompletableFuture.supplyAsync(() -> {
pause(500);
return "Alice";
});
CompletableFuture<Integer> points = CompletableFuture.supplyAsync(() -> {
pause(500);
return 120;
});
String line = name
.thenCombine(points, (n, p) -> n + " has " + p + " points")
.join();
long ms = (System.nanoTime() - start) / 1_000_000;
System.out.println(line);
System.out.println("elapsed ms: " + ms);
}
}The first line printed is Alice has 120 points. The elapsed time is a little over 500 ms, not 1000 ms, because the two sleeps overlap. The exact number varies by machine.
The type arguments follow the lambda. The future name is CompletableFuture<String>, so n is a String. The future points is CompletableFuture<Integer>, so p is an Integer. The lambda returns a String, so the result is CompletableFuture<String>.
The mistake that makes it sequential
The independence comes from when you start the futures, not from which method you call. This version looks similar but runs one task after the other:
import java.util.concurrent.CompletableFuture;
public class AccidentallySequential {
static void pause(long millis) {
try {
Thread.sleep(millis);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
public static void main(String[] args) {
long start = System.nanoTime();
String line = CompletableFuture.supplyAsync(() -> {
pause(500);
return "Alice";
})
.thenCompose(n -> CompletableFuture.supplyAsync(() -> {
pause(500);
return n + " has 120 points";
}))
.join();
long ms = (System.nanoTime() - start) / 1_000_000;
System.out.println(line);
System.out.println("elapsed ms: " + ms);
}
}The second supplyAsync is created inside the thenCompose lambda, so it only starts after the first task finishes. The elapsed time is about 1000 ms. Use thenCompose only when the second step really needs the first value. For independent work, create both futures first and then combine them.
Variants that return less
thenCombine always produces a new value. Two sibling methods cover the cases where you do not need one:
| Method | Function type | Returns | Use when |
|---|---|---|---|
| `thenCombine` | `BiFunction<T, U, V>` | `CompletableFuture<V>` | You merge two values into a new one |
| `thenAcceptBoth` | `BiConsumer<T, U>` | `CompletableFuture<Void>` | You use both values for a side effect, such as logging |
| `runAfterBoth` | `Runnable` | `CompletableFuture<Void>` | You only need to know that both finished |
import java.util.concurrent.CompletableFuture;
public class BothVariants {
public static void main(String[] args) {
CompletableFuture<String> a = CompletableFuture.supplyAsync(() -> "left");
CompletableFuture<String> b = CompletableFuture.supplyAsync(() -> "right");
a.thenAcceptBoth(b, (x, y) -> System.out.println(x + " + " + y)).join();
a.runAfterBoth(b, () -> System.out.println("both done")).join();
}
}This prints left + right and then both done.
Combining more than two futures
thenCombine takes exactly two inputs. For three values, chain it. The first call produces an intermediate future. The second call merges that with the third future.
import java.util.concurrent.CompletableFuture;
public class ThreeWay {
public static void main(String[] args) {
CompletableFuture<String> name = CompletableFuture.supplyAsync(() -> "Alice");
CompletableFuture<Integer> qty = CompletableFuture.supplyAsync(() -> 3);
CompletableFuture<Double> price = CompletableFuture.supplyAsync(() -> 9.5);
String summary = name
.thenCombine(qty, (n, q) -> n + " ordered " + q)
.thenCombine(price, (text, p) -> text + " items at " + p + " each")
.join();
System.out.println(summary);
}
}This prints Alice ordered 3 items at 9.5 each. All three futures start before the chain is built, so they still run in parallel. If you have four or more inputs, or a list of unknown size, the nesting gets awkward. Use allOf, which a later chapter covers, and read each result with join once everything has completed.
When one input fails
The combining function runs only if both futures complete normally. If either future fails, the function is skipped, and the returned future completes exceptionally.
import java.util.concurrent.CompletableFuture;
public class CombineFailure {
public static void main(String[] args) {
CompletableFuture<String> name = CompletableFuture.supplyAsync(() -> "Alice");
CompletableFuture<Integer> price = CompletableFuture.supplyAsync(() -> {
throw new IllegalStateException("price service down");
});
String result = name
.thenCombine(price, (n, p) -> {
System.out.println("never printed");
return n + " " + p;
})
.exceptionally(ex -> "fallback: " + ex.getCause().getMessage())
.join();
System.out.println(result);
}
}The output is fallback: price service down. The exceptionally handler receives a CompletionException, and the original IllegalStateException is its cause. This is the wrapping that the error-handling chapter explains in detail.
Two points about failures:
- If both futures fail, the resulting exception comes from one of them. Do not rely on which one. If you need every failure, attach
handleorwhenCompleteto each input future separately. - A failure in one future does not cancel the other. The other task keeps running and its result is discarded. If the discarded task is expensive, plan for that.
Handling one input's failure without losing the other
Often a missing value is acceptable. For example, you can show a page without recommendations. Attach a fallback to the optional input before combining. Then the combined stage always sees a value.
import java.util.concurrent.CompletableFuture;
public class OptionalInput {
public static void main(String[] args) {
CompletableFuture<String> title = CompletableFuture.supplyAsync(() -> "Report");
CompletableFuture<String> note = CompletableFuture
.<String>supplyAsync(() -> {
throw new RuntimeException("note service down");
})
.exceptionally(ex -> "(no note)");
System.out.println(title.thenCombine(note, (t, n) -> t + " " + n).join());
}
}This prints Report (no note). The explicit type witness <String> is needed because the lambda only throws, so Java cannot infer the future's element type without it.
Executors and the Async variants
thenCombine has two variants that control where the combining function runs:
thenCombineAsync(other, fn)runsfnon the common pool.thenCombineAsync(other, fn, executor)runsfnon the executor you supply.
The plain thenCombine runs fn on whichever thread completes the second of the two futures. If both were already complete when you called it, fn runs on the calling thread. For a cheap merge, such as string concatenation, this is fine. If the function is slow or blocks, use an Async variant with your own executor. Otherwise you may tie up a thread that belongs to someone else, such as a thread that completes a future for an I/O library.
Choosing between the methods
- If step B needs the value from step A, use
thenCompose. - If A and B are independent and you want a merged value, use
thenCombine. - If A and B are independent and you only need a side effect, use
thenAcceptBothorrunAfterBoth. - If you have more than two independent futures, chain
thenCombinefor three, or useallOffor many. - If you want whichever of two finishes first, use
applyToEither,acceptEither, orrunAfterEither. These mirror the "both" methods but fire on the first completion.
Exercise
The code below takes about 1000 ms, although the two tasks could overlap. Why, and how would you change it so they run in parallel? Assume slowA() and slowB() each return a CompletableFuture<Integer> and each takes 500 ms.
CompletableFuture<Integer> sum = slowA().thenCompose(a -> slowB().thenApply(b -> a + b));
Show answer
slowB() is only called inside the thenCompose lambda, so it starts after slowA() finishes. The two tasks run one after the other. Start both before combining: CompletableFuture<Integer> fa = slowA(); CompletableFuture<Integer> fb = slowB(); CompletableFuture<Integer> sum = fa.thenCombine(fb, (a, b) -> a + b); Now both run at once and the total is about 500 ms.
Exercise
You combine futures x and y with x.thenCombine(y, fn). Future y fails with an exception. Does fn run, what does the combined future do, and what type of exception does a handler on the combined future receive?
Show answer
fn does not run. The combined future completes exceptionally. A handler such as exceptionally or handle receives a CompletionException whose cause is the original exception thrown in y's task. Future x is not cancelled and keeps running.