jdk20 新特性 scoped value 的使用
注意:由于使用方式的限制,这种值的传递只能单向
由于特性还在孵化阶段 用法可能在21中有变动
static final ScopedValue<Long> scopedValue = ScopedValue.newInstance();
// test scoped value
@Test
public void testScopedValue() throws InterruptedException {
CountDownLatch latch = new CountDownLatch(1);
Thread start = Thread.ofVirtual().start(() -> {
ScopedValue.where(scopedValue, System.currentTimeMillis(), this::showMessage);
latch.countDown();
});
latch.await();
//此处会报错,因为线程start中的scopedValue已经被移除,生命周期之外scoped value不能被访问
System.out.println(scopedValue.get());
}
//此处可以在内部调用其他方法并获取scoped value,因为scopedValue已经被绑定到当前线程,注意传递是单向的,内部的变更无法在上一级获取
//此处代码来自 https://github.com/hakdogan/scoped-values
void showMessage() {
log.info(scopedValue.get().toString());
// Long request = scopedValue.get();
//
// try (var scope = new StructuredTaskScope.ShutdownOnFailure()) {
// Future<Boolean> validation = scope.fork(() -> xxx);
// Future<Boolean> account = scope.fork(() -> xxx);
//
// try {
// scope.join();
// scope.throwIfFailed();
// } catch (InterruptedException e) {
// Thread.currentThread().interrupt();
// throw new RuntimeException("This thread was interrupted!");
// } catch (ExecutionException e){
// throw new RuntimeException("An ExecutionException occurred!");
// }
//
// if(validation.resultNow() && account.resultNow()){
// getPaid();
// ScopedValue.where(scopedValue, xxx)
// .run(() -> xxx);
// }
// }
}
idea 配置
--enable-preview -source 20 --add-modules jdk.incubator.concurrent