Wednesday, August 16, 2006

Background Threads in Tomcat

I have a task that I want to run once a minute. I have it coded as a command-line app, but getting that app to run as a Windows service is getting to be a pain. And, we also have an instance of Tomcat running on that server, so I started looking at how to get it to run within Tomcat.

This made me a bit nervous at first, as Tomcat does a lot of threaded stuff on its own, and I'd really rather not step on its toes, but after a bit of searching, I found that kicking off your own threads is a fine thing to do in Tomcat, but with a couple of caveats.

First, Tomcat lets apps ("contexts" in Tomcat lingo) be hotswapped, i.e. restarted or removed and replaced with new code, without stopping the VM. This means that you need to wire up your thread to stop when the app (sorry, "context") is stopped. You can write a servlet to watch over your thread (that can actually be the thread itself, too), and have Tomcat instantiate it, by configuring it in web.xml with "<load-on-startup />" included.

The servlet itself will extend HttpServlet (of course), and implement Runnable (if it's to have the thread code in it as well, which is handy. Then, when the destroy() method is called on your servlet, you tell your thread to stop itself (i.e. via a call to Thread.interrupt(), perhaps), as the context is going away.

I found a code sample at http://classes.eclab.byu.edu/462/demos/PrimeSearcher.java that helped, although that sample is coded to call Thread.stop(), which is now deprecated.

Anyway, I now have simple thread doing background processing, nicely cooperating with Tomcat.

Labels:

2 Comments:

Blogger Unknown said...

The link is not working, would you please put the code or another link there.

Best regards

2:25 AM  
Blogger Dave said...

So sorry, I've since switched jobs, so I don't have access to that code any longer.

9:38 PM  

Post a Comment

<< Home