Java Reference
In-Depth Information
11.2.1. Converting a synchronous method into an asynchronous one
To achieve this you first have to turn the getPrice method into a getPriceAsync method and
change its return value:
public Future<Double> getPriceAsync(String product) { ... }
As we mentioned in the introduction of this chapter, the java.util.concurrent .Future interface
was introduced in Java 5 to represent the result of an asynchronous computation (that is, the
caller thread is allowed to proceed without blocking). This means a Future is just a handle for a
value that isn't yet available but can be retrieved by invoking its get method after its
computation has finally terminated. As a result, the getPriceAsync method can return
immediately, giving the caller thread a chance to perform other useful computations in the
meantime. The new CompletableFuture class gives you various possibilities to implement this
method in an easy way, for example, as shown in the next listing.
Listing 11.4. Implementing the getPriceAsync method
Here you create an instance of CompletableFuture, representing an asynchronous computation
and containing a result when it becomes available. Then you fork a different Thread that will
perform the actual price calculation and return the Future instance without waiting for that
long-lasting calculation to terminate. When the price of the requested product is finally available,
you can complete the Completable-Future using its complete method to set the value. Obviously
this feature also explains the name of this new Future implementation. A client of this API can
invoke it, as shown in the next listing.
 
Search WWH ::




Custom Search