Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Java reference

CompletableFuture.thenCombine()

Combines the results of two independent tasks once both are ready.

Available since: Java 8

Syntax

<U, V> CompletableFuture<V> thenCombine(CompletionStage<? extends U> other, BiFunction<? super T, ? super U, ? extends V> fn)

Parameters

ParameterTypeDescription
otherCompletionStage<? extends U>The second, independent task.
fnBiFunction<? super T, ? super U, ? extends V>Combines both results.

Return value

CompletableFuture<V>The combined result.

Examples

A price and an exchange rate load in parallel:

void main() {
    var price = CompletableFuture.supplyAsync(() -> 120.0);
    var rate = CompletableFuture.supplyAsync(() -> 0.92);
    double inEuro = price.thenCombine(rate, (p, r) -> p * r).join();
    IO.println(inEuro);
}

Output:

110.4

Notes

Both tasks run at the same time, so the total time equals the longest one. For any number of tasks use CompletableFuture.allOf(...) and then join() each one.

See also

Related recipes

In the tutorial

  • CompletableFuture — Asynchronous chains in Java — CompletableFuture.supplyAsync, thenApply, thenAccept, thenCombine, allOf, handling errors with exceptionally and join.

Thanks for reading!

Donate to the site — we work hard for you.