Sunday, June 1, 2014

EJB 3.1: Asynchronous Methods

New to EJB 3.1, by using the @javax.ejb.Asynchronous annotation, we can achieve fire and forget invocations, useful when having long time processing methods. When the client needs to use the result, it can take use of the facilities provided by the java.util.concurrent.Future
We can use the @Asynchronous annotation on class level, so all the methods are asynchronous, or we can use the @Asynchronous annotation at the method level.

A void method can also be marked with the @Asynchronous annotation, but in this case, no exceptions will be delivered to the client.

public Future<String> doStuff(final String input){
    // do stuff and return
    return new AsyncResult<String>("myResult");

If the asynchronous method has a return type Future<V> and it throws an exception, the the client will get an ExecutionException when trying to retrieve the result.

Cancel a request:
The client can request a cancel on the Future<V> invocation, using
Future<V>.cancel(boolean mayInterruptIfRunning)

where the boolean parameter represents if the asynchronous method can see if the cancel was requested.
The asynchronous method can check if cancel was called by the client, by using the SessionContext.wasCancelCalled()

Retrieving the results:
final Future<String> futureTask= myEjbProxyReference.doStuff(input);
final String result= futureTask.get(10,TimeUnit.SECONDS); //should catch the TimeoutException

Please notice the if the get() method is called with no arguments, then the get() will block until the result is available. To be assure that the result is retrieved after an undefined amount of time, then the Future<V>.isDone() method should be called, to check if the asynch result processing was already finished.

No comments:

Post a Comment