Java Reference
In-Depth Information
Synchronous vs. asynchronous API
The phrase synchronous API is just another way of talking about a traditional call to a method:
you call it, the caller then waits while the method computes, the method then returns, and the
caller continues with the returned value. Even if the caller and callee were executed on different
threads, the caller would still wait for the callee to complete; this gives rise to the phrase
blocking call .
In contrast, in an asynchronous API the method returns immediately, or at least before its
computation is complete, delegating its remaining computation to a thread, which runs
asynchronously to the caller—hence the phrase non-blocking call . The remaining computation
gives its value to the caller, either by calling a callback method or by the caller invoking a further
“wait until the computation is complete” method. This style of computation is common for I/O
systems programming: you initiate a disc access, which happens asynchronously while you do
more computation, and when you have nothing more useful to do, you simply wait until the disc
blocks are loaded into memory.
11.2. Implementing an asynchronous API
To start implementing the best-price-finder application, let's begin by defining the API that each
single shop should provide. First, a shop declares a method that returns the price of a product
given its name:
public class Shop {
public double getPrice(String product) {
// to be implemented
}
}
The internal implementation of this method would query the shop's database but probably also
perform other time-consuming tasks, such as contacting various other external services (for
example, the shop's suppliers or manufacturer-related promotional discounts). To fake such a
long-running method execution, in the rest of this chapter we simply use a delay method, which
introduces an artificial delay of 1 second, defined in the following listing.
Search WWH ::




Custom Search