Java Reference
In-Depth Information
Parsing the quotes
Now you have to convert those Strings into Quotes with a second transformation. But because
this parsing operation isn't invoking any remote service or doing any I/O in general, it can be
performed almost instantaneously and can be done synchronously without introducing any
delay. For this reason, you implement this second transformation by invoking the thenApply
method on the CompletableFutures produced by the first step and passing to it a Function
converting a String into an instance of Quote.
Note that using the thenApply method doesn't block your code until the Completable-Future on
which you're invoking it is completed. This means that when the Completable-Future finally
completes, you want to transform the value it contains using the lambda expression passed to
the then-Apply method, thus transforming each Completable-Future<String> in the stream into
a corresponding CompletableFuture<Quote>. You can see this as building a recipe of what to do
with the result of the CompletableFuture, just like when you were working with a stream
pipeline.
Composing the futures for calculating the discounted price
The third map operation involves contacting the remote Discount service to apply the
appropriate discount percentage to the nondiscounted prices received from the shops. This
transformation is different from the previous one because it will have to be executed remotely
(or, in this case, it will have to simulate the remote invocation with a delay), and for this reason
you also want to perform it asynchronously.
To achieve this, as you did with the first invocation of supplyAsync with getPrice, you pass this
operation as a lambda expression to the supplyAsync factory method, which will return another
CompletableFuture. At this point you have two asynchronous operations, modeled with two
distinct CompletableFutures, that you want to perform in a cascade:
Retrieve the price from a shop and then transform it into a Quote
Take this Quote and pass it to the Discount service to obtain the final discounted price
The Java 8 CompletableFutures API provides the thenCompose method specifically for this
purpose, allowing you to pipeline two asynchronous operations, passing the result of the first
operation to the second operation when it becomes available. In other words, you can compose
two CompletableFutures by invoking the thenCompose method on the first CompletableFuture
and passing to it a Function. This Function has as argument the value returned by that first
CompletableFuture when it completes, and it returns a second CompletableFuture that uses the
 
Search WWH ::




Custom Search