Java Magazine, Sept/Oct 2017
ORACLE COM JAVAMAGAZINE SEPTEMBER OCTOBER 2017 38 java 9 to GBP Both services introduce a certain delay before responding with a result This delay is due to the costs of network communication with the service You could solve this problem by making use of CompletableFuture as follows Note for advanced readers By default a CompletableFuture uses the common thread pool but this can be parameterized with an Executor using an overload of supplyAsync BigDecimal amount CompletableFuture supplyAsync findBestPrice LDN NYC thenCombine CompletableFuture supplyAsync queryExchangeRateFor GBP this convert get In this code the method convert takes the two BigDecimal results from findBestPrice and queryExchangeRateFor and calculates the final amount Timeout mechanism There are a few problems associated with the code above First get is a blocking call This means that the main thread will need to wait until the result is ready before it can progress Ideally youd like the main thread to do other useful work while the result is calculated in the background Second the main thread could be blocking indefinitely because a timeout is not specified What if one of the services is overloaded and doesnt respond To add a timeout mechanism you can use the other version of get inherited from Future which throws a TimeoutException when the overall pipeline takes longer than a specified amount of time to return the result BigDecimal amount CompletableFuture supplyAsync findBestPrice LDN NYC thenCombine CompletableFuture supplyAsync queryExchangeRateFor GBP
You must have JavaScript enabled to view digital editions.