bhylu.com

Advertisements

Java Compose an Asynchronous Result

CompletableFuture can describe what to do when a result becomes available. Keep the transformation, execution policy and failure path separate in your reasoning.

Understand the idea

thenApply transforms one successful value, while thenCompose is useful when a step itself returns a completion stage. Async-suffixed operations may schedule on an executor; non-async continuations may run on a thread completing the previous stage. A call to join waits and can throw an unchecked completion wrapper. Every chain needs an explicit policy for cancellation, timeouts and exceptions at its outer boundary.

Run it locally

Use a local JDK 21 or newer. Save the complete example as Main.java in a separate lab folder, then compile and run it with the commands below. Java examples do not run in Bhylu’s browser playground. The -ea option enables assertion checks used by some lessons.

JDK and terminal setup

javac --release 21 -encoding UTF-8 -d out Main.java
java -ea -cp out Main

A worked example

Java 21+ · Main.java

import java.util.concurrent.CompletableFuture;

public class Main {
    public static void main(String[] args) {
        CompletableFuture<Integer> seats = CompletableFuture.completedFuture(6);
        String label = seats.thenApply(count -> count + " seats ready").join();
        System.out.println(label);
    }
}

Expected output

6 seats ready

The already-completed future makes the transformation deterministic and keeps this first example focused on composition. The API name does not mean a new thread is necessarily created for every step. Replacing the source with a real asynchronous task would add lifecycle and failure considerations without changing the transformation’s basic contract.

Check the official Java documentation for detailed contracts and supported options.