ScopedValue在JDK24以及JDK25的改动

前言

ScopedValueJDK21引入的预览属性,在后续的JDK版本中一直预览,然而在JDK24和稳定版JDK25中,有些许调整

JDK24调整

JDK24去掉了runWherecallWhere方法,直接使用where方法了

csharp 复制代码
public class ScopedValueDemo {


    private static ScopedValue<String> stringScopedValue = ScopedValue.newInstance();

    public static void main(String[] args) {
        ScopedValue.where(stringScopedValue, say()).run(() -> {
            System.out.println(stringScopedValue.get());
        });
    }


    public static String say() {
        System.out.println("============say()方法");
        return "aaa";
    }

}

输出结果如下

JDK25调整,

ScopedValueJDK25正式转正了,也就是不再是预览属性了,可以正式使用了,只是有个方法做了以下调整,ScopedValue.orElse()方法不再接受null作为参数 JDK24源码

JDK25源码

java 复制代码
import java.lang.ScopedValue;

public class ScopedValueOrElseExample {

    private static final ScopedValue<String> USER_ID = ScopedValue.newInstance();

    public static void main(String[] args) {
        // 场景1:未绑定值时,使用 orElse() 提供默认值
        String userId1 = USER_ID.orElse(null);
        System.out.println("未绑定值时:" + userId1);

    }
}

输出结果为

typescript 复制代码
import java.lang.ScopedValue;

public class ScopedValueOrElseExample {

    private static final ScopedValue<String> USER_ID = ScopedValue.newInstance();

    public static void main(String[] args) {
        // 场景1:未绑定值时,使用 orElse() 提供默认值
        String userId1 = USER_ID.orElse("aaaa");
        System.out.println("未绑定值时:" + userId1); // 输出:aaaa

        // 场景2:绑定值后,orElse() 会返回绑定值
        ScopedValue.where(USER_ID, "hello world").run(() -> {
            String userId2 = USER_ID.orElse("default_user");
            System.out.println("绑定值后:" + userId2); // 输出:hello world
        });

        // 场景3:在子方法中使用 orElse()
        printUserId();
    }

    private static void printUserId() {
        // 子方法中未绑定值,使用默认值
        String userId = USER_ID.orElse("unknown_user");
        System.out.println("子方法中:" + userId); // 输出:unknown_user
    }
}

输出结果为

总结

在JDK25中,JEP 506终于转正,也就是说,ScopedValueJDK25正式转正了,也就是不再是预览属性了,可以放心大胆的使用该语法糖了,可以用来代替ThreadLocal

相关推荐
AskHarries11 小时前
SEO 页面怎么生成
后端
爱吃牛肉的大老虎12 小时前
Rust对象之结构体,枚举,特性
开发语言·后端·rust
石榴12 小时前
NestJS 的请求到底经过了什么:装饰器、守卫、拦截器、管道与中间件如何配合
后端
bbq粉刷匠12 小时前
HashMap 底层原理深度拆解(二):putVal 完整链路解析(懒加载 · 链表遍历 · 尾插法)
java·开发语言·哈希算法
Gopher_HBo12 小时前
moby-client客户端
后端
Sam_Deep_Thinking12 小时前
一个靠谱的C端网关服务应该包含什么内容
java·程序员·系统架构
杨运交12 小时前
[055][调度模块]Spring动态任务调度框架的设计与实现
java·后端·spring
白狐_79813 小时前
408 数据结构算法题 01:线性表暴力求解保分指南
java·数据结构·算法
流云鹤13 小时前
03Java学习day(3)
java·学习
tqs_1234513 小时前
Agent智能体+Skill插件引擎+Milvus混合检索 技术沉淀
java·python·milvus