Java Magazine, September/October 2017
ORACLE COM JAVAMAGAZINE SEPTEMBER OCTOBER 2017 39 java 9 this convert get 1 TimeUnit SECONDS Unfortunately this reworked code is still blocking and it prevents the main thread from doing useful work in the meantime To tackle this issue you can refactor the code to use thenAccept and provide a callback that is executed when the result is finally available as in the last line of the following code CompletableFuture supplyAsync findBestPrice LDN NYC thenCombine CompletableFuture supplyAsync queryExchangeRateFor GBP this convert thenAccept amount System out println The price is amount GBP However by using this approach you lose the timeout functionality Ideally you would like to specify a timeout using a nonblocking method There isnt built in elegant support to solve this problem in Java 8 Solutions available in Java 8 are a little clunky and include using acceptEither or applyToEither with the CompletableFuture on which you are waiting for the result using another CompletableFuture That CompletableFuture wraps a ScheduledThreadPoolExecutor that throws a TimeoutException after a specified time CompletableFuture supplyAsync findBestPrice LDN NYC thenCombine CompletableFuture supplyAsync queryExchangeRateFor GBP this convert acceptEither
You must have JavaScript enabled to view digital editions.