views:

1578

answers:

3

I am not very familiar with Tomcat, in my head it is basically abstracted as a cgi server that saves the JVM between calls -- I know it can do a lot more than that, though.

I am looking for a way to launch a background thread when a Tomcat server starts, which would periodically update the Server Context (in my particular case this is a thread that listens to heartbeats from some other services and updates availability information, but one can imagine a variety of uses for this).

Is there a standard way to do this? Both the launching, and the updating/querying of the Context?

Any pointers to the relevant documentation and/or code samples would be much appreciated.

+8  A: 

If you want to start a thread when your WAR is deployed, you can define a context listener within the web.xml:

<listener>
    <listener-class>com.mypackage.MyServletContextListener</listener-class>
</listener>

Then implement that class something like:

public class MyServletContextListener implements ServletContextListener {

    private MyThreadClass myThread = null;

    public void contextInitialized(ServletContextEvent sce) {
        if ((myThread == null) || (!myThread.isAlive())) {
            myThread = new MyThreadClass();
            myThread.start();
        }
    }

    public void contextDestroyed(ServletContextEvent sce){
        try {
            myThread.doShutdown();
            myThread.interrupt();
        } catch (Exception ex) {
        }
    }
}
Chris Thornhill
Ah! Thanks, that's very straightforward.Am I correct in saying that "ServletContext" is what I need to modify to have this thread pass information to my servlet, so it can use the statuses my heartbeat listener collects?
SquareCog
Yes, missed this part in my answer. :) The ServletConext is available from the ServletContextEvent, which could be passed into the your Thread object which could get/set attributes available to all threads.
Chris Thornhill
+2  A: 

I am looking for a way to launch a background thread when a Tomcat server starts

I think you are looking for a way to launch a background thread when your web application is started by Tomcat.

This can be done using a ServletContextListener. It is registered in web.xml and will be called when your app is started or stopped. You can then created (and later stop) your Thread, using the normal Java ways to create a Thread (or ExecutionService).

Thilo
Ah, Chris beat me to it..
Thilo
Upvoted you anyway. Thanks!
SquareCog
A: 

I'd just make a small change to the very detailed answer Chris gave; I would set myThread to be a Daemon thread by myThread.setDaemon(true); which will basically keep the thread active as long as you have other non-Daemon threads working which need your background thread around. When all these threads finish then your Daemon thread is stopped by the JVM and you do not need to handle it youself in contextDestroyed. But that's just my 2 cents.

Ittai