-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCallableFuture.java
More file actions
66 lines (56 loc) · 1.87 KB
/
CallableFuture.java
File metadata and controls
66 lines (56 loc) · 1.87 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
57
58
59
60
61
62
63
64
65
66
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
public class CallableFuture {
public static void main(String[] args) {
// Callable task can return value
Callable<Integer> task = () ->
{
try {
TimeUnit.SECONDS.sleep(2);
return 123;
} catch (InterruptedException e) {
throw new IllegalStateException("task interrupted", e);
}
};
ExecutorService executor = Executors.newFixedThreadPool(1);
Future<Integer> future = executor.submit(task);
System.out.println("future 1 done? " + future.isDone());
Integer result;
try {
// Block the current thread and waits until the callable completes
// before returning the actual result
result = future.get();
System.out.println("future 1 done? " + future.isDone());
System.out.println("result: " + result);
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
future = executor.submit(task);
try {
// Block the current thread and waits until the callable completes
// or timeout will throw exception
result = future.get(1, TimeUnit.SECONDS);
System.out.println("future 2 done? " + future.isDone());
System.out.println("result: " + result);
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
} catch (TimeoutException e) {
System.out.println("future 2 done? " + future.isDone());
System.out.println("future 2 timeout");
e.printStackTrace();
}
// Keep in mind that every non-terminated future calls get() will throw
// exceptions
// if you shutdown the executor:
executor.shutdownNow();
}
}