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

相关推荐
黒亱中旳3 小时前
Java AI 框架三国杀:Solon AI vs Spring AI vs LangChain4j 深度对比
java·人工智能·spring
网络工程小王3 小时前
[智能对话系统架构设计文档]
java·系统架构·langraph
alxraves4 小时前
医用超声远程会诊系统:会诊平台的核心架构与功能解析
java·人工智能·架构
带刺的坐椅4 小时前
用 Solon AI ReActAgent 落地智能客服工单处理
java·ai·llm·agent·solon·react-agent
我是坏垠5 小时前
Crypto、Cipher与Password:Java加密开发的三个核心概念
java·开发语言·python
white_ant5 小时前
JDK LTS 版本升级迁移注意事项大全
java·开发语言
戮漠summer6 小时前
Missing Semester 计算机教育中缺失的一课 Lecture 01 Shell
开发语言·后端·scala
广州灵眸科技有限公司6 小时前
瑞芯微RV1126B开发板(EASY-EAI-PI2) INI文件操作
java·前端·javascript·网络·人工智能
库克克7 小时前
【C++ 】内联函数
java·开发语言·c++
zh_xuan7 小时前
java 虚拟线程
java·开发语言·虚拟线程