Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

util.concurrent.StructuredTaskScope: practical reference

util.concurrent.StructuredTaskScope: practical reference: StructuredTaskScope<T> is a Java 21 preview API that confines concurrent subtask lifetimes to a structured scope.

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

Syntax

java.util.concurrent.StructuredTaskScope

StructuredTaskScope is a Java 21 preview API that confines concurrent subtask lifetimes to a structured scope.

Use try-with-resources: fork subtasks, join as the owner, inspect results or failures, and then close the scope.

It requires preview features; only the owner may call join and close, and close reports misuse if fork was not followed by join.

shutdown interrupts unfinished subtasks but requires cooperation; ShutdownOnFailure and ShutdownOnSuccess provide different short-circuit policies.

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

Examples

import java.lang.reflect.Method;
import java.util.concurrent.Callable;

public class Main {
    public static void main(String[] args) throws Exception {
        Class<?> scopeType = Class.forName("java.util.concurrent.StructuredTaskScope$ShutdownOnFailure");
        Object scope = scopeType.getConstructor().newInstance();
        try {
            Object subtask = scopeType.getMethod("fork", Callable.class)
                .invoke(scope, (Callable<Integer>) () -> 42);
            scopeType.getMethod("join").invoke(scope);
            scopeType.getMethod("throwIfFailed").invoke(scope);
            Method get = Class.forName("java.util.concurrent.StructuredTaskScope$Subtask").getMethod("get");
            System.out.println(get.invoke(subtask));
        } finally {
            scopeType.getMethod("close").invoke(scope);
        }
    }
}

Result

42

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

Sources