Enterprise Java Development@TOPIC@
Task(s) may take considerable time to complete
Client may not need to wait for task to complete
Multiple tasks could run concurrently
Client may gather results as they complete
Manually create a Java thread to complete task
Messages are processed by JMS consumers in independent threads
Establish
a JMS destination for work requests
a JMS destination for work responses
a MessageDriven Bean to perform asynchronous work
Client
builds JMS message with request information
sends JMS request message to request destination
continues working
waits for response
MessageDriven Bean
is invoked to handle the JMS request message
performs requested work
builds JMS message with response information
sends JMS response message to response destination
Client
receives JMS response message
extracts the response information
Request container to execute method in independent thread from caller
Client and called method are fully decoupled from one another
Called method executes in new transaction context
Available since EJB 3.1
Establish
an EJB method to perform work in independent thread
Annotate EJB method with @javax.ejb.Asynchronous
Alternately annotate EJB class to make all methods asynchronous
Declare return type as:
void or
java.util.concurrent.Future
import java.util.concurrent.Future;
import javax.ejb.Asynchronous;
@Stateless
public class AuctionMgmtActionEJB {
@Asynchronous
public Future<Date> doWorkAsync(long delay) {
Asynchronous methods that return "void" cannot throw application exceptions. Asynchronous methods that return "Future<T> can throw application exceptions.
Client
Invokes method normally using standard arguments
Future<Date> f = actions.doWorkAsync(delay);
Asynchronous Method
performs work
returns result information wrapped in javax.ejb.AsyncResult
javax.ejb.AsyncResult
@Asynchronous
public Future<Date> doWorkAsync(long delay) {
Date now = ...
return new AsyncResult<Date>(now);
}
AsyncResult is only a convenience class used to pass the result to the container. This instance is not accessible to the client. The client will be given an instance of a Future built and managed by the container.
Client
immediately receives Future<T> response message
may call isDone() to check on status
Future<Date> f = actions.doWorkAsync(delay);
...
f.isDone();
may call get() to check on wait for result
Future<Date> f = actions.doWorkAsync(delay);
...
Date date = f.get();