-
Notifications
You must be signed in to change notification settings - Fork 108
Expand file tree
/
Copy pathStructuredConcurrencyWithScopedValueExample.java
More file actions
56 lines (48 loc) · 1.64 KB
/
StructuredConcurrencyWithScopedValueExample.java
File metadata and controls
56 lines (48 loc) · 1.64 KB
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
import java.util.concurrent.*;
import java.util.concurrent.StructuredTaskScope.Joiner;
import java.util.concurrent.StructuredTaskScope.Subtask;
import javax.management.RuntimeErrorException;
/**
* To run: `java --source 25 --enable-preview StructuredConcurrencyWithScopedValueExample.java`
*/
public class StructuredConcurrencyWithScopedValueExample {
private final static ScopedValue<String> USER_ID = ScopedValue.newInstance();
public static void main(String[] args) {
new StructuredConcurrencyWithScopedValueExample().run();
}
public void run() {
try {
var result = ScopedValue.where(USER_ID, "neo").call(this::parallelHandle);
System.out.println(result);
} catch (Exception ex) {
ex.printStackTrace();
}
}
private String parallelHandle() throws InterruptedException, ExecutionException {
// when we create a scope, the scoped values are captured
try (var scope = StructuredTaskScope.open()) {
// the child scopes can use its parent's scoped value bindings
Subtask<String> userName = scope.fork(this::findUserName);
Subtask<String> answer = scope.fork(this::findPower);
scope.join();
return "The real name of '%s' is '%s' and its power is %s"
.formatted(USER_ID.get(), userName.get(), answer.get());
}
}
private String findUserName() {
var userId = USER_ID.get();
System.out.println("Searching name for user ID: " + userId);
try {
Thread.sleep(500);
} catch (Exception ex) {}
return userId;
}
private String findPower() {
var userId = USER_ID.get();
System.out.println("Calculating power for user ID: " + userId);
try {
Thread.sleep(3000);
} catch (Exception ex) {}
return "Over 9000";
}
}