CompletableFuture: Asynchronous Results

Keep Java's own CompletableFuture, with an Effect Path and a MonadError instance.

CompletableFuture at a glance

ModelsJava's asynchronous result, already running
ReplacesNothing: it is Java's own type
Effect PathCompletableFuturePath, shown in On a CompletableFuturePath
InstancesFunctor, Applicative, Monad, MonadError<Throwable>
Choose it whenAn API gives you a future, or the work is already running on another thread; otherwise VTask, or compare every type in Choosing a Type

What You'll Learn

  • Say when a CompletableFuture's work starts, and how that differs from IO and VTask
  • Recover from a failed lookup on a CompletableFuturePath, and say why retrying needs the work, not the future
  • Combine futures that are already running through CompletableFuture's MonadError instance
  • Say what the instance's error handler receives, and what widening a future costs

See Example Code

The code on this page is CompletableFutureBook.java: the page includes it, so the build compiles and runs it. CompletableFutureBookTest.java holds what the page says each method does.


Java's own type

java.util.concurrent.CompletableFuture is how much of Java hands back a result that is not ready yet. The work behind a future has usually started by the time you hold it, often on another thread, where an IO or a VTask waits until you run it. Its own methods, such as thenApply, thenCompose and exceptionallyCompose, already chain and recover. Higher-Kinded-J adds an Effect Path, CompletableFuturePath, with recovery, timeouts and conversions for application code. It also adds a MonadError instance, so that a method written once for any container accepts a future.

The code on this page uses these imports, with Order from the order records the Optics chapter introduces:

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.concurrent.CompletableFuture;
import org.higherkindedj.example.book.optics.cast.Order;

Pricing an order in euros needs two lookups, each from a slow service, and supplyAsync starts each on another thread at once. rateServiceDown stands in for the rate service failing:

  // Each lookup starts on another thread as soon as it is called
  static CompletableFuture<BigDecimal> rateToEuros() {
    return CompletableFuture.supplyAsync(() -> new BigDecimal("1.17"));
  }

  static CompletableFuture<BigDecimal> shippingQuote(Order order) {
    return CompletableFuture.supplyAsync(() -> new BigDecimal("7.99"));
  }

  // A lookup whose service fails
  static CompletableFuture<BigDecimal> rateServiceDown() {
    return CompletableFuture.supplyAsync(
        () -> {
          throw new IllegalStateException("the rate service is down");
        });
  }

  static BigDecimal subtotal(Order order) {
    return order.lines().stream()
        .map(line -> line.price().multiply(BigDecimal.valueOf(line.quantity())))
        .reduce(BigDecimal.ZERO, BigDecimal::add);
  }

  static BigDecimal inEuros(Order order, BigDecimal rate, BigDecimal shipping) {
    return subtotal(order).add(shipping).multiply(rate).setScale(2, RoundingMode.HALF_UP);
  }

On a CompletableFuturePath

Path.future puts a future on a CompletableFuturePath. recover gives a value in place of a failure, here CACHED_RATE, 1.15, the rate to use when the rate service cannot answer. parZipWith joins the result with another Path's, and join() waits for the answer. via chains a step that needs the previous result, as thenCompose does, and Migration Cookbook: Recipe 4 turns a nested chain into one. These are the extra imports:

import org.higherkindedj.hkt.effect.CompletableFuturePath;
import org.higherkindedj.hkt.effect.Path;
  static CompletableFuturePath<BigDecimal> priceInEuros(
      Order order, CompletableFuture<BigDecimal> rate) {
    return Path.future(rate)
        .recover(error -> CACHED_RATE)
        .parZipWith(
            Path.future(shippingQuote(order)), (r, shipping) -> inEuros(order, r, shipping));
  }

ORDER is worth 92.50 in pounds and shipping costs 7.99, so the live rate gives (92.50 + 7.99) × 1.17 = 117.57:

    BigDecimal priced = priceInEuros(ORDER, rateToEuros()).join();
    // 117.57
    BigDecimal withCachedRate = priceInEuros(ORDER, rateServiceDown()).join();
    // 115.56

A CompletableFuturePath also times out with withTimeout, which fails the Path but leaves the work behind the future running, since the timeout fails the future without cancelling it. Cancelling the Path's own future does reach the work when it wraps a future that can be interrupted, such as one from VTask.runAsync(); a map or via makes a new future, which breaks that chain. toEitherPath() waits for the future, then holds a failure as a Left. A future that has failed stays failed, so to try failed work again, start it with CompletableFuturePath.supplyAsyncWithRetry(supplier, attempts, delay), which runs the supplier again. A future that completes with null fails the Path, which catches every CompletableFuture<Void> from runAsync or allOf: map one to Unit first, with thenApply(_ -> Unit.INSTANCE).

Methods

CompletableFuture's own methods are the JDK's. The library adds these:

MethodWhat it does
Path.future(future), Path.futureAsync(supplier)Put a future on a CompletableFuturePath, or start one
Path.futureCompleted(value), Path.futureFailed(exception)Build a Path that has already succeeded, or failed with an Exception
CompletableFuturePath.supplyAsyncWithRetry(supplier, attempts, delay)Start work, and run the supplier again after a failure
map(f), via(f), recover(f)Change the value, chain a step, or give a value in place of a failure
parZipWith(other, f), race(other)Join two Paths' results, or keep whichever succeeds first, failing only if both fail
withTimeout(duration)Fails the Path if the future has not completed in time; the work behind it runs on
join(), toEitherPath()Wait for the result, or wait and then hold a failure as a Left
FUTURE.widen(future), FUTURE.narrow(kind), FUTURE.join(kind)Move a future in and out of Kind, or wait for one

Working with Kind

Generic code, written once for any container, takes a CompletableFuture through its MonadError instance, whose error type is Throwable, as MonadError shows. Each operation is one of the future's own methods:

Instance operationCompletableFuture method
map(f, fa)thenApply(f)
flatMap(f, fa)thenCompose(f)
ap(ff, fa), and map2 to map5thenCombine, completing once both have
of(value)completedFuture(value)
raiseError(error)failedFuture(error)
handleErrorWith(fa, handler)exceptionallyCompose(handler)

These are the extra imports:

import static org.higherkindedj.hkt.future.CompletableFutureKindHelper.FUTURE;
import static org.higherkindedj.hkt.instances.Witnesses.completableFuture;

import org.higherkindedj.hkt.Kind;
import org.higherkindedj.hkt.MonadError;
import org.higherkindedj.hkt.future.CompletableFutureKind;
import org.higherkindedj.hkt.instances.Instances;
    MonadError<CompletableFutureKind.Witness, Throwable> futures =
        Instances.monadError(completableFuture());

    // Both lookups are already running when map2 is called
    Kind<CompletableFutureKind.Witness, BigDecimal> price =
        futures.map2(
            FUTURE.widen(rateToEuros()),
            FUTURE.widen(shippingQuote(ORDER)),
            (rate, shipping) -> inEuros(ORDER, rate, shipping));
    BigDecimal euros = FUTURE.join(price);
    // 117.57

    Kind<CompletableFutureKind.Witness, BigDecimal> rate =
        futures.handleErrorWith(
            FUTURE.widen(rateServiceDown()),
            error -> FUTURE.widen(CompletableFuture.completedFuture(CACHED_RATE)));
    BigDecimal fallback = FUTURE.join(rate);
    // 1.15

map2 neither starts nor waits for its futures: both lookups were already running, and the future it gives completes once both have. FUTURE.join is what waits.

The handler given to handleErrorWith receives the exception that failed the future, not the CompletionException the JDK wraps it in. FUTURE.join rethrows that exception too when it is unchecked; a checked one stays wrapped. A constant fallback is shorter with recover or recoverWith, which build their fallback before the call, so a fallback future runs even when the first one succeeds.

CompletableFuture is a JDK class, so it cannot implement CompletableFutureKind: FUTURE.widen wraps it in a small holder object each time, and narrow unwraps it. The instance's of(null) keeps the JDK's null, where a CompletableFuturePath fails.

When to use CompletableFuture

You needUse
To work with APIs that already give you a CompletableFutureCompletableFuture, with CompletableFuturePath or its instance
Work that waits until you run it, on virtual threads, alone or concurrentlyVTask
A side effect that waits until you run it, on the calling threadIO
A value worked out once and kept, with no side effectLazy
Typed errors inside an asynchronous resultThe EitherT transformer

Previous: Lazy Next: VTask