Background Thread for a Tomcat servlet app [duplicate] Background Thread for a Tomcat servlet app [duplicate] multithreading multithreading

Background Thread for a Tomcat servlet app [duplicate]


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


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


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