Building a processing application with EJB’s (don’t use THREADS!)

I have for some time had to build processing applications. These normally consist of thread based things that run off and do a lot of calculations and database work. These days however I use EJB’s and the @Asynchrounous tag above a routine to make it work asynchronously.

To make it work you need to create 2 stateless session beans.

One will hold your routines that you wish to run, lets call this runnerBean, you need to create a local interface to it.

Second, create the timer bean that will start off the threads in runner bean.

In the timerBean that starts all the threads off create an @Schedule routine and a reference to the runnerBean.

@EJB
private doRunnerLocal doRunner;

@Schedule(second = “*/5”, minute = “*”, hour = “*”, persistent = false)
private void importThreadManager() {

while (true) {

List serialNos=new ArrayList();

try {
serialNos.em.createNativeQuery(“select * from serialnos where processed<1”,SerialNos.class).getResultList();
} catch (Exception e) {

}

if (serialNos.isEmpty()) {
// Have a sleep for a while if nothing found
try {
Thread.sleep(10000);
} catch (InterruptedException x) {
}
} else {
for (i=0;i<serialNos.size();++i) {
doRunner.doSomething((String)serialNos.get(i));
}
}

}

In the runner bean then create your Async threads really simply.

@Asynchronous
public void doSomthing(String serialNo) {

// Process serial numbers

}

Job Done!

Advertisements

About Paul C

I am a Senior Java programmer/Web Technologies, Play in a band called Mandolin Monday, I have a cat and I live on a boat.

Posted on August 8, 2012, in glassfish, Uncategorized. Bookmark the permalink. Leave a comment.

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s

%d bloggers like this: