JEP 543 Finalizes Structured Concurrency in JDK 28
JEP 543 has been integrated into JDK 28, promoting the StructuredTaskScope API from preview to final release with no API changes versus the seventh preview in JDK 27; migration only requires removing the --enable-preview flag and recompiling. This ends the longest preview cycle among all Loom Project features, letting library and framework maintainers build on structured concurrency without forcing users to enable preview flags.
Related Entities
Full Report
JEP 543,结构化并发(Structured Concurrency),已经被集成到 JDK 28 中,将 java.util.concurrent 包中的 StructuredTaskScope API 提升至正式发布状态,这个版本相较于 JDK 27 的第七次预览没有任何 API 层面的变更。对于已经处于 JDK 27 的代码库,迁移工作只需移除--enable-preview 参数后重新编译即可。
此次正式定稿标志着 Loom 项目所有特性中最长预览周期的结束。结构化并发最初作为孵化 API 在 JEP 428(JDK 19)和 JEP 437(JDK 20)中出现,随后经历了七次预览:JEP 453(JDK 21)、JEP 462(JDK 22)、JEP 480(JDK 23)、JEP 499(JDK 24)、JEP 505(JDK 25)、JEP 525(JDK 26)以及 JEP 533(JDK 27)。在每一次迭代中,其核心目标始终是将运行在不同线程中的一组相关子任务视为一个单一的工作单元,以确保某个子任务的失败能够取消其他子任务,并且父作用域在所有子线程终止之前无法退出。传统的 ExecutorService 和 Future 管道无法强制约束这些边界情况:父方法可以在子任务继续在后台运行时返回,而子任务的失败只有在调用方最终调用 Future.get()时才会暴露。
该 API 的核心是 StructuredTaskScope,这是一个密闭接口(sealed interface),通过静态工厂方法而非公共构造器来开启。无参的 open()工厂方法返回一个作用域,其 join()方法会等待所有子任务成功,在遇到首个失败时它会取消其余的任务,并抛出 ExecutionException:
Response handle() throws ExecutionException, InterruptedException {
try (var scope = StructuredTaskScope.open()) {
Subtask<String> user = scope.fork(() -> findUser());
Subtask<Integer> order = scope.fork(() -> fetchOrder());
scope.join(); // throws ExecutionException if either subtask fails
return new Response(user.get(), order.get());
}
}复制代码
每次 fork()调用默认会启动一个虚拟线程;join()是所有者线程等待结果的唯一汇聚点,try-with-resources 块末尾的 close()会取消所有未完成的子任务,并等待它们的线程终止。完成策略通过 Joiner接口定义:Joiner.awaitAllSuccessfulOrThrow()匹配上述的默认策略;Joiner.allSuccessfulOrThrow()针对同质子任务直接从 join()返回一个 List;Joiner.anySuccessfulOrThrow()返回首个成功的结果并取消其余的任务;Joiner.allUntil(Predicate)则在谓词匹配时取消该作用域。
正式定稿的 API 保留了在 JDK 27 中确立的完整形态。JEP 533 引入了第三个类型参数 R_X,以便 join()能够声明其 Joiner 可能抛出的特定异常类型,而不是抛出仅预览版存在的 FailedException。在内置的抛出型 joiner 下,join()会抛出 ExecutionException,这与 Future.get()长期以来使用的包装器相同。从 JDK 26 迁移的团队需要做更多改动。他们将会看到 FailedException 被替换成了 ExecutionException,并且自定义 joiner 的签名中增加了 R_X。此外,StructuredTaskScope.TimeoutException 已被移除,转而使用带有 CancelledByTimeoutException 原因的方式报告超时;Joiner.awaitAll()已经不可用了,而且 onTimeout()回调已被抽象方法 timeout()取代。自定义策略正是第三个类型参数体现其价值的地方。例如,一个等待副本读取达到法定数量的 joiner,可以抛出自定义的检查型异常:
class QuorumJoiner<T> implements Joiner<T, List<T>, QuorumException> {
private final int quorum;
private final Queue<T> results = new ConcurrentLinkedQueue<>();
QuorumJoiner(int quorum) {
this.quorum = quorum;
}
@Override
public boolean onComplete(Subtask<T> subtask) {
if (subtask.state() == Subtask.State.SUCCESS) {
results.add(subtask.get());
}
return results.size() >= quorum; // true cancels the remaining reads
}
@Override
public List<T> result() throws QuorumException {
if (results.size() < quorum) {
throw new QuorumException(results.size(), quorum);
}
return List.copyOf(results).subList(0, quorum);
}
@Override
public List<T> timeout() throws QuorumException {
throw new QuorumException(results.size(), quorum,
new CancelledByTimeoutException());
}
}
try (var scope = StructuredTaskScope.open(new QuorumJoiner<String>(2))) {
replicas.forEach(r -> scope.fork(() -> r.read(key)));
List<String> values = scope.join(); // throws QuorumException
}复制代码
因为该 joiner 将其声明的 QuorumException(一种应用定义的检查型异常)作为其 R_X,所以 join()会直接抛出该异常,而不是将其包装在 ExecutionException 中。timeout()遵循 JDK 27 的契约,抛出带有 CancelledByTimeoutException 原因的相同异常。
超时和配置语义保持不变。将 UnaryOperator传递给 open()可以配置作用域名称(用于可观测性)、自定义的 ThreadFactory,或者配置一个截止时间(如果在 join()之前或期间过期,则取消该作用域):
try (var scope = StructuredTaskScope.open(
cf -> cf.withTimeout(Duration.ofSeconds(2)).withName("profile-page"))) {
Subtask<String> user = scope.fork(() -> findUser());
Subtask<Integer> order = scope.fork(() -> fetchOrder());
scope.join();
return new Response(user.get(), order.get());
} catch (ExecutionException e) {
return switch (e.getCause()) {
case CancelledByTimeoutException _ -> handleTimeout();
case IOException ioe -> handleIo(ioe);
default -> throw e;
};
}复制代码
该 API 在结构上也非常严格。只有开启作用域的线程才能调用 fork()和 join(),执行结果只能在 join()返回后通过 Subtask.get()读取,而结构性误用(例如,乱序关闭作用域)会快速失败并抛出 StructureViolationException,而不是导致线程泄漏。为了上下文传播和调试,子任务会继承 ScopedValue 绑定(JEP 506),并在 JSON 线程转储中显示在其父线程之下。
有一个细节特意未做声明:如果多个子任务同时失败,API 并未规定 join()会报告哪一个失败。Viktor Klang 在代码审查期间提出了这个问题,甲骨文的 JEP 所有者 Alan Bateman 重写了 Javadoc,仅承诺异常必定来自某个失败的子任务。
对于处于 JDK 27 的团队,迁移到正式 API 只需要一次构建变更,而非代码变更。定稿提交仅移除了预览注解,没有更改任何方法签名,因此团队可以从 javac、测试运行器和启动脚本中移除--enable-preview,然后在包含该变更的 JDK 28 早期访问构建版本上重新编译。JDK 28 计划于 2027 年 3 月正式发布(general availability,GA)。
更大的转变在于库和框架的维护者,他们现在可以基于结构化并发进行构建,而无需强制用户开启预览标志。velo/structured-concurrency 项目已经将 JEP 543 的 API 向后移植到了 JDK 25,并提供了在升级后迁移到 JDK 原生类的迁移指南。
查看英文原文:JEP 543 Finalizes Structured Concurrency in JDK 28, Ending Seven Preview Rounds