Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

util.concurrent.CompletionStage: practical reference

util.concurrent.CompletionStage: practical reference: CompletionStage<T> describes a computation stage that performs an action or computes a value when another stage completes.

Version: Java SE 21 (JLS and Java SE API); examples verified on the repository Java runtime

Syntax

java.util.concurrent.CompletionStage

CompletionStage describes a computation stage that performs an action or computes a value when another stage completes.

Use thenApply for transformation, thenCompose to flatten a dependent stage, and handle or exceptionally for failures.

The interface is not itself a Future and guarantees neither blocking retrieval, a particular Executor, nor ordering among independent dependents.

Either-combinators do not specify which result wins, and exceptional completion propagates according to the chosen combinator.

The example exercises the documented element in a small deterministic program and compares exact standard output.

Examples

public class Main {
    public static void main(String[] args) throws Exception {
        java.util.concurrent.CompletionStage<Integer> stage = java.util.concurrent.CompletableFuture.completedFuture(6);
        System.out.println(stage.thenApply(value -> value * 7).toCompletableFuture().join());
    }
}

Result

42

The example exercises the documented element in a small deterministic program and compares exact standard output.

Sources