-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathInvokeAny.java
More file actions
42 lines (34 loc) · 1.04 KB
/
InvokeAny.java
File metadata and controls
42 lines (34 loc) · 1.04 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
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
public class InvokeAny {
public static void main(String[] args) {
ExecutorService executor = Executors.newWorkStealingPool();
List<Callable<String>> callables = Arrays.asList(
callable("task1", 2),
callable("task2", 1),
callable("task3", 3));
/*
* Instead of returning future objects
* this method blocks until the first callable terminates
* and returns the result of that callable.
*/
String result;
try {
result = executor.invokeAny(callables);
System.out.println(result);
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
}
private static Callable<String> callable(String result, long sleepSeconds) {
return () -> {
TimeUnit.SECONDS.sleep(sleepSeconds);
return result;
};
}
}