-
Notifications
You must be signed in to change notification settings - Fork 320
/
Copy pathUsingCompletableFuture.java
211 lines (199 loc) · 6.08 KB
/
UsingCompletableFuture.java
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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
package br.com.leonardoz.features.futures;
import java.util.Random;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.function.Supplier;
/**
*
* CompletableFuture is a Future that may be manually completed. It combines a
* Future interface with the CompletionStage interface, supporting dependent
* actions that trigger upon its completion, similarly to a callback.
*
* Important: Specify an Executor for async methods when available. All async
* methods without an explicit Executor argument are performed using the
* ForkJoinPool.commonPool();
*
* Important 2: Mostly of the CompletableFuture methods returns a new
* CompletableFuture.
*
* == Quick terminology guide ==
*
* = Async =
*
* xxxAsync(...); // Async method executed in the ForkJoinPool.commonPool();
*
* xxxAsync(..., Executor executor); // Executed in the specified Executor, good
* for Java EE.
*
*
* = supply x run =
*
* supplyAsync(Supplier<U> supplier); // will complete asynchronously by calling
* supplier.
*
* runAsync(Runnable runnable); // will complete after the runnable executions;
*
*
* = thenApply x thenAccept x thenRun
*
* thenApply: transforms a value to another type;
*
* thenAccept: accepts a consumer to the result value;
*
* thenRun: accepts a Runnable to be executed after the result is ready;
*
*
* == Quick API guide ==
*
* = Creating =
*
* new CompletableFuture<>();
*
* CompletableFuture.supplyAsync(Supplier<U>supplier);
*
* CompletableFuture.supplyAsync(Supplier<U> supplier, Executor executor);
*
* CompletableFuture.runAsync(Runnable runnable);
*
* CompletableFuture.runAsync(Runnable runnable, Executor executor);
*
*
* = Mapping values =
*
* completableFuture.thenApply(Function<? super T,? extends U> fn);
*
* completableFuture.thenApplyAsync(Function<? super T,? extends U> fn);
*
* completableFuture.thenApplyAsync(Function<? super T,? extends U> fn, Executor
* executor);
*
*
* = Callback on completion =
*
* completableFuture.thenAccept(Consumer<? super T> block);
*
* completableFuture.thenRun(Runnable action);
*
*
* = Error handling =
*
* completableFuture.exceptionally(ex -> ex.getMessage());
*
* completableFuture.handle((value, ex) -> {if value != null... else {}})
*
*
* = Pipeline =
*
* Chain one future dependent on the other
*
* completableFuture.thenCompose(Function<? super T,CompletableFuture<U>> fn);
* // flatMap
*
*
* = Mapping values from Two Futures =
*
* completableFuture.thenCombine(CompletableFuture<? extends U> other,
* BiFunction<? super T,? super U,? extends V> fn) ex.:
*
*
* = Waiting for first CompletableFuture to complete =
*
* Two services, one fast and the other slow. Fastest always wins.
*
* completableFuture.acceptEither(CompletableFuture<? extends T> other,
* Consumer<? super T> block);
*
*
* = Transforming first completed =
*
* completableFuture.applyToEither(CompletableFuture<? extends T> other,
* Function<? super T,U> fn)
*
*
* = Combining multiple CompletableFuture together =
*
* CompletableFuture.allOf(CompletableFuture<?>... cfs)
*
* CompletableFuture.anyOf(CompletableFuture<?>... cfs)
*
*
* = Get-Complete value =
*
* CompletableFuture.get() // block
*
* CompletableFuture.complete() // complete future's lifecycle
*
* CompletableFuture.obtrudeValue() // ignores complete
*
* CompletableFuture.join() // same as get
*
* CompletableFuture.getNow(valueIfAbsent) // immediately return
*
* CompletableFuture.completeExceptionally() // completes throwing a exception
*
* CompletableFuture.completeExceptionally(ex) // completes with a exception
*
*/
public class UsingCompletableFuture {
public static void main(String[] args) throws InterruptedException, ExecutionException {
var random = new Random();
var executor = Executors.newCachedThreadPool();
// Creating
CompletableFuture<Integer> randomNum = CompletableFuture.supplyAsync(() -> random.nextInt(140), executor);
// Mapping
String strNum = randomNum.thenApplyAsync(n -> Integer.toString(n), executor).get();
System.out.println("Executed " + strNum);
// Combining
CompletableFuture<Integer> anotherNum = CompletableFuture.supplyAsync(() -> random.nextInt(140), executor);
// accept both and do something
randomNum.thenAcceptBoth(anotherNum, (num1, num2) -> {
System.out.println("Num1 is: " + num1);
System.out.println("Num2 is: " + num2);
});
// combine both into a new type/value
CompletableFuture<Integer> mappedAndCombined = randomNum.thenCombine(anotherNum, (num1, num2) -> num1 + num2);
// retrieving value
Integer value = mappedAndCombined.get();
System.out.println("Sum " + value);
// Undefined time task
Supplier<Double> randomDouble = () -> {
try {
Thread.sleep(random.nextInt(1000));
} catch (InterruptedException e) {
e.printStackTrace();
}
return random.nextDouble();
};
// Run after executed
CompletableFuture<Double> f1 = CompletableFuture.supplyAsync(randomDouble);
CompletableFuture<Double> f2 = CompletableFuture.supplyAsync(randomDouble);
CompletableFuture<Double> f3 = CompletableFuture.supplyAsync(randomDouble);
CompletableFuture<Double> f4 = CompletableFuture.supplyAsync(randomDouble);
CompletableFuture.anyOf(f1, f2, f3, f4).thenRun(() -> System.out.println("Completed"));
// Fastest result will be delivered
// Undefined time task - static value
Supplier<String> getVal = () -> {
try {
Thread.sleep(random.nextInt(1000));
} catch (InterruptedException e) {
e.printStackTrace();
}
return "First";
};
Supplier<String> getVal2 = () -> {
try {
Thread.sleep(random.nextInt(1000));
} catch (InterruptedException e) {
e.printStackTrace();
}
return "Second";
};
CompletableFuture
.supplyAsync(getVal)
.acceptEitherAsync(CompletableFuture.supplyAsync(getVal2, executor), (firstToBeReady) -> System.out.println(firstToBeReady), executor);
executor.shutdown();
executor.awaitTermination(3000, TimeUnit.SECONDS);
}
}