Structrued Concurrency

Structrued concurrency put multiple tasks in to a scope. If a task fails, the scope automatically cancels other tasks within it.

import java.util.concurrent.StructuredTaskScope;
import java.util.concurrent.ExecutionException;

void main() throws InterruptedException, ExecutionException {

    try (var scope = new StructuredTaskScope.ShutdownOnFailure()) {

        var task1 = scope.fork(() -> {
            Thread.sleep(2000);
            System.out.println("Task 1 Completed");
            return 1;
        });

        var task2 = scope.fork(() -> {
            Thread.sleep(1000);
            return 1 / 0;
        });

        var task3 = scope.fork(() -> {
            Thread.sleep(500);
            System.out.println("Task 3 Completed");
            return null;
        });

        scope.join().throwIfFailed();;
    } catch (Exception e) {
        System.err.println("Exception while executing tasks: " + e.getMessage());
    }
}

It's still in preview as of java 23, you need to pass the --enable-preview flag:

java --enable-preview Main.java                                                                                                             <<<

Expected output:

Task 3 Completed
Exception while executing tasks: java.lang.ArithmeticException: / by zero