Java Magazine, September/October 2017
ORACLE COM JAVAMAGAZINE SEPTEMBER OCTOBER 2017 41 java 9 It internally uses a ScheduledThreadExecutor and completes the CompletableFuture with a TimeoutException after the specified timeout has elapsed It also returns another CompletableFuture meaning that you can further chain your computation pipeline and deal with the TimeoutException by providing a friendly message back for example CompletableFuture supplyAsync findBestPrice LDN NYC thenCombine CompletableFuture supplyAsync queryExchangeRateFor GBP this convert orTimeout 1 TimeUnit SECONDS whenComplete amount error if error null System out println The price is amount GBP else System out println Sorry we could not return you a result The method completeOnTimeout has the following signature public CompletableFuture T completeOnTimeout T value long timeout TimeUnit unit It also uses a ScheduledThreadExecutor internally but in contrast to orTimeout it provides a default value in the event that the CompletableFuture pipeline times out The orTimeout method is conceptually similar to the orElse method using java util Optional In the following code if the services are slow to respond a default price is provided otherwise the result of combining the two services is returned
You must have JavaScript enabled to view digital editions.