CompletableFuture for Concurrent Composition
Uses CompletableFuture to compose asynchronous operations with thenApply, thenCompose, thenCombine, and exception handling for non-blocking pipelines.
Code
import java.util.concurrent.*;
import java.util.List;
public class CompletableFutureExample {
static CompletableFuture<String> fetchUserName(int id) {
return CompletableFuture.supplyAsync(() -> {
sleep(200);
return "User" + id;
});
}
static CompletableFuture<Integer> fetchUserScore(String name) {
return CompletableFuture.supplyAsync(() -> {
sleep(300);
return name.length() * 10;
});
}
static void sleep(int ms) {
try { Thread.sleep(ms); } catch (InterruptedException e) {}
}
public static void main(String[] args) throws Exception {
CompletableFuture<String> pipeline = fetchUserName(42)
.thenCompose(CompletableFutureExample::fetchUserScore)
.thenApply(score -> "Score: " + score)
.exceptionally(ex -> "Error: " + ex.getMessage());
System.out.println(pipeline.get());
CompletableFuture<String> f1 = CompletableFuture.supplyAsync(() -> "Hello");
CompletableFuture<String> f2 = CompletableFuture.supplyAsync(() -> "World");
String combined = f1.thenCombine(f2, (a, b) -> a + " " + b).get();
System.out.println("Combined: " + combined);
List<CompletableFuture<String>> futures = List.of(
CompletableFuture.supplyAsync(() -> "Task1"),
CompletableFuture.supplyAsync(() -> "Task2"),
CompletableFuture.supplyAsync(() -> "Task3")
);
CompletableFuture<Void> all = CompletableFuture.allOf(
futures.toArray(new CompletableFuture[0])
);
all.thenRun(() -> System.out.println("All tasks done")).get();
}
}What the code does
Count the class CompletableFutureExample and the functions fetchUserName, fetchUserScore and sleep as the entire surface area of CompletableFuture for Concurrent Composition.
Applying it
Entry signature: static CompletableFuture<String> fetchUserName(int id)
Look for the Combined:, All tasks done prefixes when the file runs; they tie each line to its step.
Treat main as the orchestrator calling fetchUserName in a fixed order.
Statements that matter
try { Thread.sleep(ms); } catch (InterruptedException e) {}
return CompletableFuture.supplyAsync(() -> {
sleep(200);
return "User" + id;
});
return CompletableFuture.supplyAsync(() -> {
sleep(300);
return name.length() * 10;
});
FAQ
- What does CompletableFuture for Concurrent Composition print when run?
- The script runs standalone; its 2 labeled outputs include `Combined:`, `All tasks done`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.