Background Thread for a Tomcat servlet app

JavaMultithreadingTomcat

Java Problem Overview


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.

Java Solutions


Solution 1 - Java

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

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

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) {
        }
    }
}

Solution 2 - Java

> 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).

Solution 3 - Java

Putting <load-on-startup>1</load-on-startup> in the <servlet> block in your web.xml will force your servlet's init() to happen as soon as Tomcat starts up, rather than waiting for the first request to arrive. This is useful if you want to spawn the background thread from init().

Solution 4 - Java

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.

Solution 5 - Java

Another way if you are using spring based framework you can specify the class/thread which you want to initialize in the beans.xml. So when the tomcat starts up, beans.xml will initialize all the classes mentioned in it. You can also pass constructor arguments if required. Below is the example of the same.

beans.xml

<bean id="monitoringSvc" class="com.mypackage.MonitoringService">
	<constructor-arg value="60"></constructor-arg>
</bean>

MonitoringService.java

public class MonitoringService{

     private MyThread myThread;

     public MonitoringService(int seconds){
          myThread = new MyThread(seconds);
          myThread.start();
     }
}    

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSquareCogView Question on Stackoverflow
Solution 1 - JavaChris ThornhillView Answer on Stackoverflow
Solution 2 - JavaThiloView Answer on Stackoverflow
Solution 3 - JavadivbyzeroView Answer on Stackoverflow
Solution 4 - JavaIttaiView Answer on Stackoverflow
Solution 5 - JavaAkshayView Answer on Stackoverflow