Java Reference
In-Depth Information
Returning a Future object to the client
The other available option consists of returning a java.util.concurrent.Future
object, which can later be inspected by our clients so that they know the outcome of our
transaction. This is shown in the following code snippet:
public Future<String> bookSeatAsync(int seatId) {
try {
return new AsyncResult<>("Booked seat: " +
seatId + ". Money left: " + money);
} catch (NoSuchSeatException | SeatBookedException
| NotEnoughMoneyException | InterruptedException e) {
return new AsyncResult<>(e.getMessage());
In this case, calls to the asynchronous bookSeatAsync method simply results, behind
the scenes, in a Runnable or Callable Java object being created, which wraps the
method and parameters you provide. This Runnable (or callable) object is given to an
Executor object, which is simply a work queue attached to a thread pool.
After adding the work to the queue, the proxy version of the method returns a Future im-
plementation that is linked to Runnable , which is now waiting in the queue.
When Runnable finally executes the bookSeatAsync method, it takes the return
value and sets it to Future , making it available to the caller.
When dealing with Future objects, the client code needs to be adapted. As a matter of
fact, in standard synchronous calls, we used exceptions to intercept some events such as
when the customer does not have enough money to complete the transaction. When using
Future calls, there's a change in this paradigm. The call to the asynchronous method is
detached from the client; however, we have the option to check if the Future work has
been completed with the isDone method issued on the Future return value.
Search WWH ::

Custom Search