Java Reference
In-Depth Information
from another query.” But implementing this with the operations available in a Future is a
different story. This is why more declarative features would be useful, such as these:
Combining two asynchronous computations in one—both when they're independent and when the
second depends on the result of the first
Waiting for the completion of all tasks performed by a set of Future s
Waiting for the completion of only the quickest task in a set of Future s (possibly because they're
trying to calculate the same value in different ways) and retrieving its result
Programmatically completing a Future (that is, by manually providing the result of the asynchronous
operation)
Reacting to a Future completion (that is, being notified when the completion happens and then
having the ability to perform a further action using the result of the Future , instead of being blocked
waiting for its result)
In this chapter, you'll learn how the new CompletableFuture class (which implements the Future
interface) makes all of this possible in a declarative way using Java 8's new features. The designs
of Stream and CompletableFuture follow similar patterns: both use lambda expressions and the
idea of pipelining. For this reason you could say that CompletableFuture is to a plain Future
what Stream is to a Collection.
11.1.2. Using CompletableFutures to build an asynchronous application
To demonstrate the CompletableFuture features, we incrementally develop a best-price-finder
application that contacts multiple online shops to find the lowest price for a given product or
service. Along the way, you'll learn several important skills:
First, you'll learn how to provide an asynchronous API for your customers (useful if you're the owner
of one of the online shops).
Second, you'll learn how to make your code non-blocking when you're a consumer of a synchronous
API. You'll discover how to pipeline two subsequent asynchronous operations, merging them into a
single asynchronous computation. This situation would arise, for example, when the online shop
returns a discount code along with the original price of the item you wanted to buy—so you have to
contact a second remote discount service to find out the percentage discount associated with this
discount code before finally calculating the actual price of that item.
You'll also learn how to reactively process events representing the completion of an asynchronous
operation and how that allows the best-price-finder application to constantly update the best-buy
quote for the item you want to buy as each shop returns its price, instead of having to wait for all the
shops to return their respective quotes (which also risks giving the user a blank screen forever if one of
the shops' servers is down).
 
Search WWH ::




Custom Search