Asynchronous Method Invocation Using CDI

EJB makes it easy to invoke a method asynchronously using the @javax.ejb.Asynchronous annotation. But, what if you are not using EJB. Can we create an equivalent annotation using CDI? The answer is yes and it is quite simple.

They key is the use of the interface java.util.concurrent.ScheduledExecutorService. Introduced in Java 1.5, classes implementing this interface allow us the schedule execution of code any time in the future without the use of EJB timer beans. Which is awesome!

We will first write a singleton class that creates a scheduler thread pool and dispatches Runnables for execution there.

@ApplicationScoped //Singleton
public class ScheduleManager {
   private ScheduledExecutorService scheduler;
   private Logger logger = Logger.getLogger(getClass().getName());

   public void init() {"Starting up scheduler.");
      scheduler = Executors.newScheduledThreadPool(3);
   public void cleanup() {"Shutting down scheduler.");
   public void schedule(Runnable r, int secondsLater) {
      scheduler.schedule(r, secondsLater, TimeUnit.SECONDS);

Now, we will write the CDI interceptor. First comes the interface for the annotation.

public @interface SimpleAsync {

Then the implementation.

public class SimpleAsyncImpl {
    ScheduleManager sm;
    Logger logger = Logger.getLogger(getClass().getName());

    public Object callAsync(final InvocationContext ctx) throws Exception {
        logger.fine("Invoking asynchronous method: " + ctx.getMethod().getName());
        //Schedule 0 seconds from now
        sm.schedule(new Runnable() {
            public void run() {
                try {
                } catch (Exception e) {
                        "Exception from asynchronously invoked method.", e);
        }, 0);

        return null;

Finally, you must register all interceptors in beans.xml. Otherwise, they wont take effect.


Now, you can decorate a method with @SimpleAsync to show the intention that the method should be invoked asynchronously.

public class A {
    public void longRunningMethod() {...}

public class B {
    A a;

    public void method() {
        a.longRunningMethod();//Will be called asynchronously

And, that’s there to it.


One thought on “Asynchronous Method Invocation Using CDI

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s