Java Reference
In-Depth Information
have enough money to buy this ticket!");
}
logger.info("Booking issued");
theatreBox.buyTicket(seat);
money = money -seat.getPrice();
return new AsyncResult<String>("Booked seat:
"+seat+" - Money left: "+money);
}
In this case, calls to the asynchronous
bookSeatAsync
method simply result, be-
hind the scenes, in a
Runnable
Java object being created that wraps the method
and parameters you provide. This
Runnable
object is given to an
Executor
object
that 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
Fu-
ture
implementation that is linked to
Runnable
that is now waiting on 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 transac-
tion. 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.
For this purpose, let's add a
bookasync
command that will issue asynchronous
booking and a
mail
command that will simulate the reading of the outcome by e-
mail:
Future<String> futureResult = null; [1]
. . . . .