A Thread pattern for JBoss Enterprise applications

Using Threads in your Enterprise applications has been traditionally discouraged as it might conflict with the Application Server’s own threads. Nevertheless with the introduction of the Asynchronous EJBs it is possible to explore new design patterns which allow managing your thread pool from within the EJB container.

 

 Important notice: this tutorial requires JBoss AS 7.2 (EAP 6.1) in order to run, since the AS 7.1.1 distribution does now allow deploying EJB which implement Runnable. See https://issues.jboss.org/browse/AS7-6088  

So let’s start from this simple Legacy code which performs a Math summation and uses a Runnable interface to perform the computation:

public class MyRunnable implements Runnable {
    private final long countUntil;

    MyRunnable(long countUntil) {
        this.countUntil = countUntil;
    }

    @Override
    public void run() {
        System.out.println("Goint to perform Summation!");  
        long sum = 0;
        for (long i = 1; i < countUntil; i++) {
            sum += i;
        }
        System.out.println("Result: " +sum);
    }
} 

So what about using an EJB to execute this operation in a set of Threads ? For this purpose we will use the Executor framework, which provides an implementation of the java.util.concurrent.Executor interface such as Executors.newFixedThreadPool(int n) that which will create n worker threads. The ExecutorService adds lifecycle methods to the Executor, which allows to shutdown the Executor and to wait for termination.

So let’s suppose you want to execute your summation as part of a pool of 5 threads:

package com.sample;

import javax.ejb.Asynchronous;
import javax.ejb.Stateless;
import java.util.concurrent.Executor;

@Stateless 
public   class ExecutorBean implements Executor {

    @Asynchronous
    @Override
    public void execute(Runnable command) {
        ExecutorService executor = Executors.newFixedThreadPool(5);
        executor.execute(command);
    }
}

Triggering your execution from a Java EE component such as a Servlet is trivial:

@EJB
private Executor executor;
 
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Runnable worker = new MyRunnable(100);
        executor.execute(worker);

    }

    
As you can see, using the Executor pattern together with Async EJBs can be an efficient way to integrate some legacy applications in your Enterprise applications. Feel free to share your opinion about it! I’d like to thanks David Blevins for sharing his thoughts about this pattern on StackOverflow