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

相关推荐
copyer_xyf13 小时前
Agent 流程编排
后端·python·agent
copyer_xyf13 小时前
Agent RAG
后端·python·agent
copyer_xyf13 小时前
【RAG】向量数据库:milvus
后端·python·agent
铁皮饭盒13 小时前
Bun 哪比 Node.js 快?
javascript·后端
copyer_xyf13 小时前
Agent 记忆管理
后端·python·agent
葫芦和十三20 小时前
图解 MongoDB 02|BSON:你以为存的是 JSON,其实是带类型的二进制
后端·mongodb·agent
葫芦和十三20 小时前
图解 MongoDB 01|文档数据库
后端·mongodb·agent
陈随易1 天前
VSCode的Copilot扩展支持接入DeepSeek,Kimi了!
前端·后端·程序员
我不是外星人1 天前
有了 Harness Engineering ,真的还需要研发工程师吗?
前端·后端·ai编程
candyTong1 天前
RTK 技术原理:一次典型会话里,80% 上下文是怎么省下来的
javascript·后端·架构