Skip to workspace
Kotlin Lab

Kotlin on the JVM / Chapter 04

Give concurrent work an owner

Start two independent lookups together and end both with the departure-board request.

The decision

A departure card needs a station and a platform. Start both independent lookups before waiting. Render the station first even when the platform arrives first. If either child throws an ordinary failure, cancel its unfinished sibling and wait for cleanup.

Read the Kotlin

Create both children before waiting for values

async creates a child and returns a Deferred. await() suspends the caller when the value is still pending. If the first await comes before the second async, the second lookup cannot start during the first wait. Create both children first. Their I/O can overlap even on a single thread when one child suspends.

val weather = async { fetchWeather() }
val alerts = async { fetchAlerts() }
render(weather.await(), alerts.await())

Trace a sibling failure through cleanup

In an ordinary coroutineScope, a child’s non-cancellation exception cancels its siblings. A suspended sibling resumes with cancellation and executes its finally blocks. The caller outside the scope sees the failure after the children finish. To understand when a file is safe to reuse, trace the sibling’s cleanup as well as the line that threw.

Choose an owner for partial success

Two independent panels can share the screen’s lifetime while handling service failures separately. Within supervisorScope, a failing child does not automatically cancel its sibling. Each failed await still needs handling so the scope body can return both outcomes. Cancelling the screen cancels its supervised children too. Recover from the service errors you intend to display and let caller cancellation propagate.

The full example

Java 25
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.function.Consumer;
import java.util.function.Supplier;

class Lesson {
    static CompletableFuture<String> departure(
            Supplier<CompletableFuture<String>> station,
            Supplier<CompletableFuture<String>> platform) {
        var name = station.get();
        var track = platform.get();
        var card = new CompletableFuture<String>();

        var failed = new AtomicBoolean();
        Consumer<Throwable> fail = error -> {
            if (failed.compareAndSet(false, true)) {
                name.cancel(false);
                track.cancel(false);
                card.completeExceptionally(error);
            }
        };
        name.whenComplete((v, error) -> { if (error != null) fail.accept(error); });
        track.whenComplete((v, error) -> { if (error != null) fail.accept(error); });
        name.thenAcceptBoth(track, (a, b) -> card.complete(a + " / " + b));
        return card;
    }
}
Kotlin/JVM
import kotlinx.coroutines.*

suspend fun departure(
    station: suspend () -> String,
    platform: suspend () -> String
): String = coroutineScope {
    val name = async { station() }
    val track = async { platform() }
    "${name.await()} / ${track.await()}"
}

Inputs and outcomes

InputOutcomeWhy it matters
Station = Lille, platform = 4Lille / 4Both lookups succeed.
Platform 9 arrives before station LyonLyon / 9Results belong to their request slots, irrespective of arrival order.
Platform fails while station is awaiting a replyThe call fails and the station request is cancelledThe caller can handle the failure after the children finish.

Walk through the code

  1. The Java suppliers return already-started futures and report producer failures through them. thenAcceptBoth receives station first. The first failure handler cancels the sibling future and completes the card with the original error. Stopping a Java producer and waiting for its cleanup require a producer-specific protocol.
  2. With one child, val name = async { station() } gives the request a Deferred<String>. name.await() suspends the caller until the value is ready. Add the platform child before that first await and both lookups can make progress. The named positions in the output keep station first.
  3. coroutineScope ties both children to this call. An ordinary child failure cancels the sibling and the scope waits for its cleanup before rethrowing. Cancelling the caller also cancels both children. A producer must cooperate with cancellation to stop its work.

The Java habit

Writing "${station()} / ${platform()}" in a suspend function still performs the calls in sequence. The modifier permits suspension at a call site. It does not schedule independent work.

When to choose differently

If the platform service needs the station ID returned by the first call, the work has a data dependency. Sequential suspension expresses that relationship directly and avoids an unnecessary child.

References

Open quizTry code