Thursday, May 3, 2012

Asynchronous Methods in EJB


In this blog I will write about Asynchronous methods in EJBs. Will write an application where we will demonstrate how to access asynchronous methods in EJB.
Asynchronous methods are new in EJB 3.1. This can be achieved by an annotation named @Asynchronous. The annotation can be applied to class level & method level as well. See the code snippet below.

@Stateless
@LocalBean
@Asynchronous
public class ServicesBean {

@Asynchronous
public void sendEmailAsync(final String recepient) {

When we annotate a method in EJB with @Asynchronous annotation, the EJB container executes the method in an asynchronous manner. The caller of the async method doesn't have to wait until the completion of the async method execution. 

@Asynchronous
   public void sendEmailAsync(final String recepient) {
        //perform all activities related to
        //the mailing actvity
        LOG.info("strat of sendEmailAsync");
        /*
        below code snippet is to show case
        a long running process. Don't use
        it in real time
        */
        try {
            Thread.sleep(4000l);
        } catch (InterruptedException ex) {
            LOG.log(Level.SEVERE, null, ex);
        }
        LOG.info("end of sendEmailAsync");
    } If we observe the above code block, the complete execution of the block will take minimum of 4 seconds
 (For demonstration purpose I have used Thead.sleep(), please don't use such code blocks).
 In normal scenarios if we invoke this method in synchronous way, then the caller has to wait for
minimum of 4 seconds.Which will impact heavily on the performance of whole application.

Through the asynchronous capability of EJBs, we can avoid  this problems.

Handling Asynchronous method Responses:
If the async method returns some value or object, then the value/object needs to be sent 
through java.util.concurrent.Future. Please see the code below.
public Future executeComputationAsync(final String employeeid){ 
          return new AsyncResult(100);
}
In the above method the return type is an Future object of type Integer.
The AsyncResult class is part of javax.ejb package & implement the Future interface.
To get the resulting info from the Future object, we can invoke the get() method of Future
object. Please see the code below.
Future result = servicesBean.executeComputationAsync("213");
int res = result.get();
out.println("Async result is " + res);
In the below video, I have demonstrated developing & accessing asynchronous methods in EJB.


The complete working code can be found here.

No comments:

Post a Comment