Tech Interview RoomStudy guides

Java 21

Java 21: Fan out to several suppliers with a timeout and pick the cheapest quote. Compare CompletableFuture, invokeAll on virtual threads and structured concurrency.

Advanced · 2 min read · Lesson 5 of 8 in Java 21

Problem

Ask three suppliers for a price in parallel. One is slow and one sometimes fails. Return the cheapest quote that arrives within 300 ms, never leaking background work after you return.

java
import java.util.concurrent.ThreadLocalRandom;

record Quote(String supplier, long pricePaise) {}

record Supplier(String name, long latencyMs, long pricePaise, boolean fails) {
    Quote quote() throws InterruptedException {
        Thread.sleep(latencyMs);
        if (fails) throw new IllegalStateException(name + " unavailable");
        return new Quote(name, pricePaise);
    }
}

Approach 1: CompletableFuture with per-call timeouts (Java 8 + 9)

Works, but the slow call keeps running in the pool after you return (cancelling a CompletableFuture does not interrupt its task), and error handling is spread across callbacks.

java
import java.util.List;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.Comparator;

class QuotesCompletable {
    static Optional<Quote> cheapest(List<Supplier> suppliers, ExecutorService pool) {
        List<CompletableFuture<Optional<Quote>>> calls = suppliers.stream()
            .map(s -> CompletableFuture.supplyAsync(() -> {
                    try { return Optional.of(s.quote()); }
                    catch (Exception e) { return Optional.<Quote>empty(); }
                }, pool)
                .completeOnTimeout(Optional.empty(), 300, TimeUnit.MILLISECONDS))
            .toList();
        return calls.stream().map(CompletableFuture::join).flatMap(Optional::stream)
            .min(Comparator.comparingLong(Quote::pricePaise));
    }
}

Approach 2: invokeAll with a timeout on a virtual-thread executor (Java 21, no preview)

invokeAll(tasks, timeout) waits up to the deadline and cancels (interrupts) tasks that have not finished. Closing the executor waits for everything to stop, so nothing leaks.

java
import java.util.Comparator;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;

class QuotesInvokeAll {
    static Optional<Quote> cheapest(List<Supplier> suppliers) throws InterruptedException {
        List<Callable<Quote>> tasks = suppliers.stream().<Callable<Quote>>map(s -> s::quote).toList();
        try (ExecutorService executor = Executors.newVirtualThreadPerTaskExecutor()) {
            List<Future<Quote>> results = executor.invokeAll(tasks, 300, TimeUnit.MILLISECONDS);
            return results.stream()
                .filter(f -> f.state() == Future.State.SUCCESS)          // Java 19+: no try/catch around get()
                .map(Future::resultNow)
                .min(Comparator.comparingLong(Quote::pricePaise));
        }
    }
}

Approach 3: Structured concurrency (Java 21 preview, JEP 453)

Subtasks are forked inside a scope that cannot outlive the block: when the scope closes, unfinished subtasks are cancelled, and thread dumps show the parent-child relationship. joinUntil applies a deadline. Requires --enable-preview on Java 21, and the API changed in Java 25 (StructuredTaskScope.open(Joiner...)), so treat it as a forward-looking answer.

java
// preview: compile and run with --enable-preview on Java 21
import java.time.Instant;
import java.util.Comparator;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.StructuredTaskScope;
import java.util.concurrent.TimeoutException;

class QuotesStructured {
    static Optional<Quote> cheapest(List<Supplier> suppliers) throws InterruptedException {
        try (var scope = new StructuredTaskScope<Quote>()) {
            List<StructuredTaskScope.Subtask<Quote>> subtasks = suppliers.stream()
                .map(s -> scope.fork(s::quote)).toList();
            try {
                scope.joinUntil(Instant.now().plusMillis(300));
            } catch (TimeoutException e) {
                scope.shutdown();   // deadline reached: cancel the stragglers...
                scope.join();       // ...and join again (returns at once) so results may be read
            }
            return subtasks.stream()
                .filter(t -> t.state() == StructuredTaskScope.Subtask.State.SUCCESS)
                .map(StructuredTaskScope.Subtask::get)
                .min(Comparator.comparingLong(Quote::pricePaise));
        }   // scope closed: no subtask can outlive this method
    }
}

class QuotesDemo {
    public static void main(String[] args) throws Exception {
        List<Supplier> suppliers = List.of(
            new Supplier("fast-cheap", 80, 9_900, false),
            new Supplier("slow-cheapest", 2_000, 8_000, false),     // misses the deadline
            new Supplier("broken", 50, 7_000, true));               // fails
        var pool = java.util.concurrent.Executors.newFixedThreadPool(4);
        long t = System.nanoTime();
        System.out.println(QuotesCompletable.cheapest(suppliers, pool) + " in " + (System.nanoTime() - t) / 1_000_000 + " ms");
        pool.shutdownNow();
        t = System.nanoTime();
        System.out.println(QuotesInvokeAll.cheapest(suppliers) + " in " + (System.nanoTime() - t) / 1_000_000 + " ms");
        t = System.nanoTime();
        System.out.println(QuotesStructured.cheapest(suppliers) + " in " + (System.nanoTime() - t) / 1_000_000 + " ms");
        // each prints Optional[Quote[supplier=fast-cheap, pricePaise=9900]] in ~300 ms
    }
}

Feasible → optimal

  1. CompletableFuture: correct result, but abandoned work keeps running and consuming resources.
  2. invokeAll with a timeout on virtual threads: cancels stragglers, simple blocking style, production-ready on Java 21 without preview flags.
  3. Structured concurrency: the clearest lifetime guarantees and observability; preview in 21, still evolving, so use it once it is final in your JDK.

Follow-up questions interviewers ask

Try answering each one before you open it.

What does "structured" concurrency guarantee that plain executors do not?

That concurrent subtasks have a lexical lifetime, like a method call: they start inside a block and are guaranteed finished (or cancelled) when it exits. Errors and cancellation propagate parent to children (with ShutdownOnFailure, one failure cancels the siblings), and thread dumps show the task tree. With raw executors, a forgotten future can keep running after the request has completed.

What are ScopedValues and why are they paired with virtual threads?

ScopedValue (preview in 21) shares immutable, per-request data (user, tenant, trace id) with callees and with structured subtasks, bound for a well-defined scope. Unlike ThreadLocal it cannot be mutated by callees, needs no remove() (no leaks in thread pools), and is cheap to inherit across millions of virtual threads.