-
Notifications
You must be signed in to change notification settings - Fork 0
/
GmoCompletableFutureDemo2.java
59 lines (44 loc) · 2.19 KB
/
GmoCompletableFutureDemo2.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
package challenge2.java8;
import externalLegacyCodeNotUnderOurControl.PriceService;
import java.util.concurrent.*;
import java.util.function.Supplier;
import static externalLegacyCodeNotUnderOurControl.PrintlnWithThreadname.println;
public class GmoCompletableFutureDemo2 {
private static final ScheduledExecutorService schedulerExecutor = Executors.newScheduledThreadPool(1); //corePoolSize - the number of threads to keep in the pool, even if they are idle size = 1
private static final ExecutorService executorService = Executors.newCachedThreadPool();
public static void main(String[] args) throws InterruptedException {
Supplier<Integer> priceSupplier = () -> new PriceService(5).getPrice();
int fallbackPrice = 42;
supplyAsyncWithTimeout(
priceSupplier,
2, TimeUnit.SECONDS,
fallbackPrice
).thenAccept(price -> println("Got price: " + price));
println("I wasn't blocked");
TimeUnit.SECONDS.sleep(10);
println("Shutting down thread pools");
executorService.shutdown();
schedulerExecutor.shutdown();
}
//Inspired by http://stackoverflow.com/questions/23575067/timeout-with-default-value-in-java-8-completablefuture/24457111#24457111
//and https://github.com/ReactiveMeetupLucerne/AsyncNonBlockingExamplesJVM/issues/8
public static <T> CompletableFuture<T> supplyAsyncWithTimeout(final Supplier<T> supplier, long timeoutValue, TimeUnit timeUnit, T defaultValue) {
final CompletableFuture<T> cf = new CompletableFuture<>();
Future<?> future = executorService.submit(() -> {
try {
cf.complete(supplier.get());
} catch (Throwable ex) {
cf.completeExceptionally(ex);
}
});
//schedule watcher (for timeout)
schedulerExecutor.schedule(() -> {
if (!cf.isDone()) {
println("Fallback to default value due timeout: " + defaultValue);
cf.complete(defaultValue);
future.cancel(true);
}
}, timeoutValue, timeUnit);
return cf;
}
}