27 March, 2013

Asynchronous methods executed not via Container

   I’m preparing to OCPJBCD currently, so I will start my blogging with topic related to this exam. It is about using asynchronous methods.
package pl.mariusz.marciniak.bean;

import javax.annotation.Resource;
import javax.ejb.Asynchronous;
import javax.ejb.SessionContext;
import javax.ejb.Stateless;

@Stateless
public class AsynchMethodBeanTest {
 
 @Resource
 SessionContext beanContext;
 
 @Asynchronous
 public void asynchMethod() {
  try {
   Thread.sleep(1000);
  } catch (InterruptedException e) {
   e.printStackTrace();
  }
 }
 
 public void invokeMethod() {
  long time = System.currentTimeMillis();
  asynchMethod();
  System.out.println("Execution time :"+(System.currentTimeMillis()-time));
  
 }
}

Do you know what will be the output, if we execute invokeMethod method?
...
...
...

The answer can be "Execution time :1001". For sure it will be value not lower than 1000. It is because execution is out of the container, so it is not asynchronous in fact. How we can change it? We can replace invokeMethod with one below.
public void invokeMethod() {
  long time = System.currentTimeMillis();
  beanContext.getBusinessObject(AsynchMethodBeanTest.class).asynchMethod();
  System.out.println("Execution time :"+(System.currentTimeMillis()-time));
 }
Now it took 2 ms on my machine. Hope you like it.

No comments:

Post a Comment