Codectionary / Developer documentation / Java

CompletableFuture Pipelines

CompletableFuture composes dependent computations. thenApply transforms a result, while thenCompose flattens an operation that itself returns a future. Save as Main.java and run with a Java 17+ JDK: java Main.java.

Syntax

future.thenApply(transform).thenCompose(asyncStep)

Examples

CompletableFuture Pipelines

Save as Main.java and run with a Java 17+ JDK: java Main.java.

import java.util.concurrent.CompletableFuture;

public class Main {
  public static void main(String[] args) throws Exception {
    CompletableFuture<Integer> result = CompletableFuture.completedFuture(5)
        .thenApply(n -> n * 2)
        .thenCompose(n -> CompletableFuture.completedFuture(n + 1));
    System.out.println(result.join());
  }
}
  1. Expected output: 11
  2. The chain starts with 5, transforms it to 10, then flattens the future containing 11. These already-completed stages do not require a background thread.

Best practices

  • Use explicit executors for asynchronous work that needs workload isolation.
  • Handle exceptional completion and avoid blocking joins inside constrained executor tasks.

Runtime & versions

Java Virtual Machine. Feature availability depends on the language and runtime version used by your project; consult the official reference below.

Java Language Specification

Specifications & further reading