Ideally the Tomcat container should manage this long running thread. i.e Tomcat should be aware of the background thread particularly for stopping a web application completely (stopping the background thread) but also for metrics gathering.
I implement long running threads as HttpServlets and start them in my ant build via the
public abstract class RunnableServlet extends HttpServlet {
private Runnable runnable;
public RunnableServlet(Runnable runnable) {
this.runnable = runnable;
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
String command = req.getParameter("command");
// continue with the task but with the container aware of this thread
if ("start".equals(command)) {
response.getOutputStream().write("started");
response.getOutputStream().close();
runnable.run();
}
}
}
By the way to use the above servlet extend it!