Java Reference
In-Depth Information
Listing 11.5. Using an asynchronous API
As you can see, the client asks the shop to get the price of a certain product. Because the shop
provides an asynchronous API, this invocation almost immediately returns the Future, through
which the client can retrieve the product's price at a later time. This allows the client to do other
tasks, like querying other shops, instead of remaining blocked waiting for the first shop to
produce the requested result. Later, when there are no other meaningful jobs that the client
could do without having the product price, it can invoke get on the Future. By doing so the client
either unwraps the value contained in the Future (if the asynchronous task is already finished)
or remains blocked until that value is available. The output produced by the code in listing 11.5
could be something like this:
Invocation returned after 43 msecs
Price is 123.26
Price returned after 1045 msecs
You can see that the invocation of the getPriceAsync method returns far sooner than when the
price calculation eventually finishes. In section 11.4 you'll learn that it's also possible for the
client to avoid any risk of being blocked. Instead it can just be notified when the Future is
completed, and execute a callback code, defined through a lambda expression or a method
reference, only when the result of the computation is available. For now we'll address another
problem: how to correctly manage the possibility of an error occurring during the execution of
the asynchronous task.
 
Search WWH ::




Custom Search