Asynchronous timeouts with CompletableFutures in Java 8 and Java 9
Java 8 introduced CompletableFuture<T>
as an enhancement to Future<T>
. It is a new class which lets you express the flow of information from different tasks using a callback driven style. A CompletableFuture
is used for defining computations on singular events, which is a different use case than computations on streams of events (e.g. Observable
using RxJava). In this article, you will learn about the problem with timeouts in Java 8's CompletableFuture and the improvements that Java 9 brings.
Combining two services
For the purpose of this article, let's say you'd like to combine the result of two services over the network:
- A best price finder for a flight route
- An exchange service that converts USD to GBP
Both of these services will introduce a certain delay before responding back with a result. This is due to the costs of network communication with the service.
You could solve this problem by making use of CompletableFuture as follows (by default a CompletableFuture uses the common thread pool but this can be parametrised with an Executor
using an overload of supplyAsync
):
Read full article from Asynchronous timeouts with CompletableFutures in Java 8 and Java 9
No comments:
Post a Comment