Skip to content

Commit 2b87146

Browse files
Java 21 Scoped Value
1 parent 1144bd9 commit 2b87146

File tree

1 file changed

+103
-0
lines changed

1 file changed

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

0 commit comments

Comments
 (0)