JDK 27 Structured Concurrency Gains Timeout and Fail-Fast in Preview
Foreword
With the release of JDK 27, structured concurrency also gets new syntax. A demo of JDK 27 structured concurrency (StructuredTaskScope, preview feature JEP 533): run two tasks in parallel and set a timeout.
JDK 27 Structured Concurrency
import java.util.concurrent.*;
import java.time.Duration;
public class StructuredDemo {
static void main() throws Exception {
// Default fail-fast strategy + 2 second timeout
try (var scope = StructuredTaskScope.open(
cfg -> cfg.withTimeout(Duration.ofSeconds(2)))) {
StructuredTaskScope.Subtask<String> task1 = scope.fork(() -> {
Thread.sleep(5000);
return "Result A";
});
StructuredTaskScope.Subtask<String> task2 = scope.fork(() -> {
Thread.sleep(300);
return "Result B";
});
scope.join();
System.out.println(task1.get() + " | " + task2.get());
} catch (ExecutionException e) {
e.printStackTrace();
}
}
}
Output result:
import java.util.concurrent.*;
import java.time.Duration;
public class StructuredDemo {
static void main() throws Exception {
// Default fail-fast strategy + 2 second timeout
try (var scope = StructuredTaskScope.open(
cfg -> cfg.withTimeout(Duration.ofSeconds(2)))) {
StructuredTaskScope.Subtask<String> task1 = scope.fork(() -> {
Thread.sleep(1000);
return "Result A";
});
StructuredTaskScope.Subtask<String> task2 = scope.fork(() -> {
Thread.sleep(300);
return "Result B";
});
scope.join();
System.out.println(task1.get() + " | " + task2.get());
} catch (ExecutionException e) {
e.printStackTrace();
}
}
}
Output result:
Conclusion
Structured concurrency can set a timeout duration, but in JDK 27 it is still a preview feature and requires enabling the preview feature.
Top 1 from juejin.cn, machine-translated. The original thread is authoritative.
Like.