// 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());
}
//此处可以在内部调用其他方法,因为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);
// }
// }
}
```java
java 新特性 scoped value 的使用
发布时间 2023-04-06 18:03:32作者: 大哥超帅