Java Reference
In-Depth Information
Listing 11.2. A method to simulate a 1-second delay
public static void delay() {
try {
Thread.sleep(1000L);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
For the purpose of this chapter, the getPrice method can be modeled by calling delay and then
returning a randomly calculated value for the price, as shown in the next listing. The code for
returning a randomly calculated price may look like a bit of a hack. It randomizes the price
based on the product name by using the result of charAt as a number.
Listing 11.3. Introducing a simulated delay in the
getPrice
method
public double getPrice(String product) {
return calculatePrice(product);
}
private double calculatePrice(String product) {
delay();
return random.nextDouble() * product.charAt(0) + product.charAt(1);
}
This implies that when the consumer of this API (in this case, the best-price-finder application)
invokes this method, it will remain blocked and then idle for 1 second while waiting for its
synchronous completion. This is unacceptable, especially considering that the best-price-finder
application will have to repeat this operation for all the shops in its network. In the subsequent
sections of this chapter, you'll discover how you can resolve this problem by consuming this
synchronous API in an asynchronous way. But for the purpose of learning how to design an
asynchronous API, we continue this section by pretending to be on the other side of the
barricade: you're a wise shop owner who realizes how painful this synchronous API is for its
users and you want to rewrite it as an asynchronous API to make your customers' lives easier.
Search WWH ::
Custom Search