Skip to content
KALANBLON
Show contents

Chapter 5 of 7 · 20 min

CompletableFuture and virtual threads

By the end of this chapter, you'll be able to

  • Start asynchronous computations with CompletableFuture.supplyAsync
  • Combine results with thenApply, thenCombine and allOf
  • Handle an asynchronous error with exceptionally
  • Run thousands of blocking tasks with virtual threads

Composing tasks with CompletableFuture

A Future can only wait. A CompletableFuture composes: "when this result arrives, transform it", "when these two results are in, combine them", "on error, offer a fallback value".

import java.util.concurrent.CompletableFuture;

double exchangeRate(String currency) {
    pause(150);
    return switch (currency) {
        case "XOF" -> 655.957;
        case "KES" -> 151.2;
        default -> throw new IllegalArgumentException("unknown currency: " + currency);
    };
}

double priceInEuros(String product) {
    pause(150);
    return product.equals("solar panel") ? 120.0 : 15.0;
}

void pause(long ms) {
    try {
        Thread.sleep(ms);
    } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
    }
}

void main() {
    CompletableFuture<Double> price = CompletableFuture.supplyAsync(() -> priceInEuros("solar panel"));
    CompletableFuture<Double> rate = CompletableFuture.supplyAsync(() -> exchangeRate("XOF"));
    double inCfa = price.thenCombine(rate, (p, r) -> p * r).join();
    IO.println(String.format("Price: %.0f CFA francs", inCfa));

    CompletableFuture<String> fallback = CompletableFuture
        .supplyAsync(() -> exchangeRate("ZZZ"))
        .thenApply(r -> "rate: " + r)
        .exceptionally(e -> "rate unavailable (" + e.getCause().getMessage() + ")");
    IO.println(fallback.join());

    List<CompletableFuture<Double>> all = List.of("XOF", "KES").stream()
        .map(c -> CompletableFuture.supplyAsync(() -> exchangeRate(c)))
        .toList();
    CompletableFuture.allOf(all.toArray(new CompletableFuture[0])).join();
    IO.println(all.stream().map(CompletableFuture::join).toList());
}
Price: 78715 CFA francs
rate unavailable (unknown currency: ZZZ)
[655.957, 151.2]
  • supplyAsync(() -> …) starts the computation on another thread and returns immediately. The two 150 ms calls run at the same time.
  • thenCombine(other, (a, b) -> …) waits for both results and combines them; thenApply transforms a result.
  • join() waits for the final result. Unlike get(), it doesn't throw a checked exception.
  • exceptionally(e -> …) intercepts an error that occurred anywhere upstream and provides a fallback value. The exception received is a CompletionException wrapping the original one, hence e.getCause().
  • allOf(…) waits for all the futures to finish; each result is then read without waiting.
  • Thread.sleep throws InterruptedException: if you catch it, restore the interrupt flag with Thread.currentThread().interrupt(), so the calling code knows it was asked to stop.

join retrieves the final result.

Step 6 of 6
Text description of the animation
  1. The first call goes off on a thread of the common pool.
  2. The second goes straight away, without waiting for the first.
  3. Both answers arrive at almost the same time…
  4. …instead of 300 ms when calling them one after the other.
  5. thenCombine applies the function as soon as both values are in.
  6. join retrieves the final result.

Virtual threads

A classic thread (called a platform thread) maps to an operating-system thread: it reserves about 1 MB of stack, and a few thousand are enough to saturate a machine. A virtual thread is managed by the JVM: it costs only a few hundred bytes while it waits, and when it blocks (network read, sleep, database query), the JVM frees the system thread that was carrying it to move another one forward.

import java.time.Duration;
import java.time.Instant;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;

void main() {
    AtomicInteger done = new AtomicInteger();
    Instant start = Instant.now();
    try (ExecutorService executor = Executors.newVirtualThreadPerTaskExecutor()) {
        for (int i = 0; i < 10_000; i++) {
            executor.submit(() -> {
                Thread.sleep(Duration.ofMillis(200));
                return done.incrementAndGet();
            });
        }
    }
    Duration elapsed = Duration.between(start, Instant.now());
    IO.println(done.get() + " tasks completed");
    IO.println("under 5 seconds? " + (elapsed.toSeconds() < 5));
}
10000 tasks completed
under 5 seconds? true

10,000 tasks that each wait 200 ms finish in a few hundred milliseconds in total. With a pool of 8 platform threads, it would take 10,000 × 200 / 8 = 250 seconds.

When to use them:

  • Yes for tasks that wait a lot: HTTP calls, databases, files. The typical case is a web server.
  • No for pure computation (the sum of squares from the previous chapter): there's nothing to gain beyond the number of cores, and a fixed pool is a better fit.
  • Never put virtual threads in a pool: create one per task, they're designed to be disposable. To limit access to a scarce resource (10 database connections, for example), use a Semaphore.

Your turn

Worked exercise

Solved exercise: the best price in time

Three suppliers answer a price request with different delays. Write Optional<Double> bestPrice(List<Offer> offers, long maxDelayMs), which queries them in parallel and returns the lowest price among those that answered in time. A supplier that is too slow is ignored. Use virtual threads and completeOnTimeout.

Hint 1
CompletableFuture.supplyAsync(task, executor) uses the executor of your choice. completeOnTimeout(value, delay, TimeUnit.MILLISECONDS) completes the future with value if the result hasn't arrived in time.
Hint 2
Choose Double.NaN as the fallback value, filter it out with !p.isNaN(), then min(Double::compare).
Show the solution and common mistakes
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

record Offer(String supplier, long delayMs, double price) {
    double query() {
        try {
            Thread.sleep(delayMs);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
        return price;
    }
}

Optional<Double> bestPrice(List<Offer> offers, long maxDelayMs) {
    try (var executor = Executors.newVirtualThreadPerTaskExecutor()) {
        List<CompletableFuture<Double>> answers = offers.stream()
            .map(o -> CompletableFuture.supplyAsync(o::query, executor)
                .completeOnTimeout(Double.NaN, maxDelayMs, TimeUnit.MILLISECONDS))
            .toList();
        return answers.stream()
            .map(CompletableFuture::join)
            .filter(p -> !p.isNaN())
            .min(Double::compare);
    }
}

void main() {
    List<Offer> offers = List.of(new Offer("Accra Trade", 50, 42.0), new Offer("Lima Import", 600, 35.0), new Offer("Hanoi Supply", 100, 39.5));
    IO.println("Best price: " + bestPrice(offers, 300).orElse(-1.0));
    IO.println("Waiting 1 s: " + bestPrice(offers, 1000).orElse(-1.0));
    IO.println("With 10 ms: " + bestPrice(offers, 10).map(String::valueOf).orElse("no answer"));
}
Best price: 39.5
Waiting 1 s: 35.0
With 10 ms: no answer

The intermediate toList() is essential: it starts all the calls before the first join. Notice too that closing the executor waits for the tasks to finish, even the ones we gave up on: the method returns its result after 600 ms. To really stop them, you would have to cancel them (cancel) and have query react to the interruption.

Common mistakes:

  • Chaining supplyAsync(…).join() inside a single map: each call waits for the previous one, and the parallelism disappears.
  • Using orTimeout instead of completeOnTimeout: the future fails with a (wrapped) TimeoutException, which then has to be handled.

Summary

  1. 1supplyAsync starts a computation in the background; thenApply, thenCombine and allOf compose the results.
  2. 2exceptionally provides a fallback value; the error received wraps the real cause.
  3. 3join and get wrap the original exception: look at getCause().
  4. 4Virtual threads make thousands of waiting tasks cheap (network, database, files).
  5. 5One virtual thread per task, never a pool; for pure computation, a fixed pool is enough.

Your progress is saved on this device. Create a free account to keep your progress on all your devices.