12.07.2015 Views

Beginning Java EE 6 with GlassFish 3, Second Edition

Beginning Java EE 6 with GlassFish 3, Second Edition

Beginning Java EE 6 with GlassFish 3, Second Edition

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

CHAPTER 7 ■ SESSION BEANS AND THE TIMER SERVICEListing 7-17. An OrderEJB That Declares Two Asynchronous Methods@Statelesspublic class OrderEJB {@Asynchronouspublic void sendEmailOrderComplete(Order order, Customer customer) {// Send e-mail}}@Asynchronouspublic void printOrder(Order order) {// Print order}When a client invokes either the printOrder() or sendEmailOrderComplete() method, the containerreturns control to the client immediately and continues processing the invocation on a separate threadof execution. As you can see in Listing 7-17, the return type of the two asynchronous methods is void.This might be suitable in a vast majority of use cases, but sometimes you need a method to return avalue. An asynchronous method can return void as well as a java.util.concurrent.Future object,where V represents the result value. Future objects allow you to obtain a return value from a methodexecuted in a separate thread. The client can then use the Future API to get the result or even cancel thecall.Listing 7-18 shows an example of a method that returns a Future. ThesendOrderToWorkflow() method uses a workflow to process an Order object. Let’s imagine that it callsseveral enterprise components (messages, web services, etc.), and each step returns a status (an integer).When the client invokes the sendOrderToWorkflow() method asynchronously, it expects to receive thestatus of the workflow. The client can retrieve the result using the Future.get() method, or, if for anyreason it wants to cancel the call, it can use Future.cancel(). If a client invokes Future.cancel(), thecontainer will attempt to cancel the asynchronous call only if that call has not already started. Noticethat the sendOrderToWorkflow() method uses the SessionContext.wasCancelCalled() method to checkwhether the client has requested to cancel the call or not. As a result, the method returnsjavax.ejb.AsyncResult, which is a convenient implementation of Future. Bear in mind thatAsyncResult is used as a way to pass the result value to the container, not directly to the caller.Listing 7-18. An OrderEJB Declares Two Asynchronous Methods@Stateless@Asynchronouspublic class OrderEJB {@ResourceSessionContext ctx;public void sendEmailOrderComplete(Order order, Customer customer) {// Send e-mail}227

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!