Files
javademos/docs/07-structured-concurrency.md

1.6 KiB

7. Structured concurrency (JEP 533, seventh preview)

Prev: 6. Lazy constants · Next: 8. PEM

Compile and run with --enable-preview --release 27. Source: StructuredDemo, transcript 21.

The 27 API, as exercised:

try (var scope = StructuredTaskScope.open(Joiner.<String>allSuccessfulOrThrow())) {
    scope.fork(StructuredDemo::fetchPrice);
    scope.fork(StructuredDemo::fetchStock);
    List<String> results = scope.join();          // [price=42, stock=7], in fork order
}
  • A failing subtask makes join() throw ExecutionException with the original as its cause.
  • New in 27: StructuredTaskScope and Joiner gained a third type parameter, the exception join() throws. Joiner.<String, OrderFailed>allSuccessfulOrThrow(OrderFailed::new) makes join() throw your type.
  • A timeout is a scope option (cfg -> cfg.withTimeout(Duration.ofMillis(100))) and surfaces as CancelledByTimeoutException.

What broke from 26

StructuredScope26.java compiles on 26 and fails on 27 with three errors (20-broken-structuredscope26.txt): wrong number of type arguments; required 3, and FailedException / TimeoutException no longer exist as nested classes (51: removed StructuredTaskScope$FailedException, $TimeoutException; added $CancelledByTimeoutException).

Prev: 6. Lazy constants · Next: 8. PEM