前言

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

JDK24调整

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

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";
    }

}

输出结果如下

image.png

JDK25调整,

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

image.png JDK25源码

image.png

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);

    }
}

输出结果为

image.png

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
    }
}

输出结果为

image.png

总结

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

本站提供的所有下载资源均来自互联网,仅提供学习交流使用,版权归原作者所有。如需商业使用,请联系原作者获得授权。 如您发现有涉嫌侵权的内容,请联系我们 邮箱:[email protected]