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

相关推荐
SomeB1oody12 分钟前
【RustyML入门】7.3. 性能调优与并行
开发语言·后端·机器学习·rust·教程
Java后端的Ai之路13 分钟前
01、Python - 设计模式介绍
java·人工智能·python·设计模式·通用
zzzll111113 分钟前
大模型技术原理与应用实践
java·数据库·人工智能
手握风云-16 分钟前
Spring Cloud:分布式系统的“粘合剂”(六)
后端·spring·spring cloud
asdfg125896318 分钟前
java.util包中的ArrayList&&Collections的目的和用途
java·arraylist·collections
余额瞒着我当琳19 分钟前
C++STL--list底层实现,迭代器分类,模拟list的迭代器封装、实现
java·开发语言·c++
吴声子夜歌25 分钟前
Java面试——数据结构(二)
java·数据结构·面试
BingoGo29 分钟前
NativePHP v4 让 Blade 构建原生 iOS 与 Android 界面
后端·php
栀栀栀栀栀栀30 分钟前
2026/8/23 maven springboot
java·spring boot·maven
程序员爱钓鱼36 分钟前
Go 编程实战:闭包 Closure——函数如何记住外部变量
后端·google·go