Java: CompletableFuture for async composition

CompletableFuture runs work off-thread and lets you chain transformations.

Code
CompletableFuture<Integer> future = CompletableFuture
        .supplyAsync(() -> 21)
        .thenApply(n -> n * 2);
System.out.println("result = " + future.join());
Output
result = 42
Advertisement

Run this yourself in the Online Java Compiler, spin up a live REST API in the API Sandbox, or practise with Java interview questions.

Published 2026-07-26