forked from janbodnar/Java-Advanced
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTheyApply.java
More file actions
59 lines (45 loc) · 1.67 KB
/
TheyApply.java
File metadata and controls
59 lines (45 loc) · 1.67 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
package com.zetcode;
import java.util.Random;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;
import java.util.function.Supplier;
public class TheyApply {
// A random supplier that sleeps for a second, and then returns
// a random value
public static class RandomSupplier implements Supplier<Integer> {
@Override
public Integer get() {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return new Random().nextInt(10);
}
}
// A (pure) function that adds one to a given Integer
public static class AddOne implements Function<Integer, Integer> {
@Override
public Integer apply(Integer x) {
return x + 1;
}
}
public static void main(String[] args) throws Exception {
ExecutorService exec = Executors.newSingleThreadExecutor();
CompletableFuture<Integer> future = CompletableFuture.supplyAsync(new RandomSupplier(), exec);
System.out.println(future.isDone()); // false
CompletableFuture<Integer> f2 = future.thenApply(new AddOne());
System.out.println(f2.get()); // Waits until the "calculation" is done and prints the result
exec.shutdown();
try {
if (!exec.awaitTermination(4, TimeUnit.SECONDS)) {
exec.shutdownNow();
}
} catch (InterruptedException e) {
exec.shutdownNow();
}
}
}