Asynchronous Methods
New in the EJB 3.1 Specification is the feature of
fire-and-forget invocations upon session beans. Often we’ll have
requirements where a request may take some time to be fully processed, and
the client may not need to wait for the result or confirmation of
completion. In these cases, we can take advantage of the new
@javax.ejb.Asynchronous
annotation to return control to
the client before EJB is invoked. When the client does need access to the
return value, it can do so via the facilities provided by
java.util.concurrent.Future
.
In the case of our EncryptionEJB, perhaps we have a very intensive hashing function that takes some time to complete:
/** * Returns a one-way hash of the specified argument, calculated asynchronously. * Useful for safely storing passwords. * * @param input * @return * @throws IllegalArgumentException * @throws EncryptionException */ Future<String> hashAsync(String input) throws IllegalArgumentException, EncryptionException;
During implementation, the bean provider may mark this method
(either on the business interface or the bean class) as @Asynchronous
, wrapping the real return
value in a convenience
implementation of java.util.concurrent.Future
called javax.
ejb.
Async
Result
:
@Asynchronous @Override public Future<String> hashAsync(final String input) throws IllegalArgumentException, EncryptionException { // Get the real hash final String hash = this.hash(input); // Wrap and return return new AsyncResult<String>(hash); }
Client usage therefore ...
Get Enterprise JavaBeans 3.1, 6th Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.