/
ScopedValueTest.java
97 lines (69 loc) · 2.73 KB
/
ScopedValueTest.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
package com.howtodoinjava.newFeatures.java21;
import java.util.concurrent.StructuredTaskScope;
public class ScopedValueTest {
//public static ThreadLocal<String> CONTEXT = ThreadLocal.withInitial(() -> null);
//public static InheritableThreadLocal<String> CONTEXT = new InheritableThreadLocal<>();
private static final ScopedValue<String> CONTEXT = ScopedValue.newInstance();
public static void main(String[] args) {
ScopedValue.runWhere(CONTEXT, "TestValue", () -> {
doSomething();
try (var scope = new StructuredTaskScope<String>()) {
scope.fork(() -> doSomethingInChildThread());
try {
scope.join();
} catch (InterruptedException ex) {
//...
}
}
});
}
static void doSomething() {
System.out.println(STR."Scoped Value in doSomething(): \{CONTEXT.get()}");
}
static String doSomethingInChildThread() {
System.out.println(STR."Scoped Value in insideChildThread(): \{CONTEXT.get()}");
return CONTEXT.get();
}
/*ScopedValueTest instance = new ScopedValueTest();
ScopedValue.runWhere(CONTEXT, "Test Value", () -> {
System.out.println("In parent thread start the scoped value is: " + CONTEXT.get());
instance.doSomething();
System.out.println("In parent thread end the scoped value is: " + CONTEXT.get());
});
System.out.println("Outside bounded scope isBound() is: " + CONTEXT.isBound());
System.out.println("Outside bounded scope the scoped value is: " + CONTEXT.orElse(null));
Thread parentThread = new Thread(() -> {
//CONTEXT.set("TestValue");
insideParentThread_1();
Thread childThread = new Thread(() -> {
insideChildThread();
});
childThread.start();
insideParentThread_2();
});
parentThread.start();
}*/
/*public void doSomething() {
System.out.println("In doSomething() and parent scope: " + CONTEXT.get());
ScopedValue.runWhere(CONTEXT, "Changed Value", () -> {
System.out.println("In doSomething() and child scope: " + CONTEXT.get());
doSomethingAgain();
});
}
public void doSomethingAgain() {
System.out.println("In doSomethingAgain() and child scope: " + CONTEXT.get());
}
static void doSomething1() {
System.out.println("Scoped Value in doSomething(): " + CONTEXT.get());
}
static void insideParentThread_1() {
System.out.println("ThreadLocal Value in insideParentThread_1(): " + CONTEXT.get());
}
static void insideParentThread_2() {
System.out.println("ThreadLocal Value in insideParentThread_2(): " + CONTEXT.get());
}
static String insideChildThread() {
System.out.println("Scoped Value in insideChildThread(): " + CONTEXT.get());
return CONTEXT.get();
}*/
}