JDK27结构化并发

前言

随着JDK27发布,结构化并发也有新的语法,JDK 27 结构化并发(StructuredTaskScope,预览特性 JEP 533) 的演示:并行跑两个任务,并可以设置超时

JDK27结构化并发

java 复制代码
import java.util.concurrent.*;
import java.time.Duration;

public class StructuredDemo {
    static void main() throws Exception {
        // 默认快速失败策略 + 2秒超时
        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();
        }
    }
}

输出结果为

java 复制代码
import java.util.concurrent.*;
import java.time.Duration;

public class StructuredDemo {
    static void main() throws Exception {
        // 默认快速失败策略 + 2秒超时
        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();
        }
    }
}

输出结果为

总结

结构化并发可以设置超时时长,但是目前在JDK27还属于预览属性,需要开启预览特性

相关推荐
沐言人生19 分钟前
自媒体人的效率神器!监控、采集、下载、发布,这个免费开源工具全拿下!
前端·vue.js·后端
我叫黑大帅2 小时前
拒绝加字段堆屎山!利用位掩码与流程编排优雅落地 上图下文 复合状态
后端·算法·面试
一条Go2 小时前
Grafana 面板嵌入:为什么 kiosk 必须是「裸参数」
后端·github
Cosolar3 小时前
监控指标全正常,订单接口从 80ms 涨到 4s 故障复盘
java·后端·面试
代码丰5 小时前
不依赖 LangGraph,也能实现 Human-in-the-loop:基于数据库状态机的人机协作工作流-CSDN博客
后端·架构
IT_陈寒5 小时前
Java实战技巧总结:当你的finally块没有执行时会发生什么?
前端·人工智能·后端
Csvn6 小时前
Nginx 与 OpenResty:阶段钩子、shared dict 与动态 upstream/证书
后端·nginx
geovindu7 小时前
rust: Functional Options Pattern
开发语言·后端·设计模式·rust·函数式选项模式·惯用法型模式
Java与AI落地7 小时前
RAG 第二步:检索质量不行,先别换模型
后端