The functional requirement is unclear, but to answer the actual question: yes, it is possible to start the background process in the servletcontainer.
If you want to use the background thread in the application, use the ServletContextListener to connect to the start up and shutdown of the webapp and use the ExecutorService to start it.
@WebListener public class Config implements ServletContextListener { private ExecutorService executor; public void contextInitialized(ServletContextEvent event) { executor = Executors.newSingleThreadExecutor(); executor.submit(new Task());
If you are not already on Servlet 3.0 and therefore cannot use @WebListener , register it as follows web.xml :
<listener> <listener-class>com.example.Config</listener-class> </listener>
If you want to use a common background thread, use the HttpSessionBindingListener to start and stop it.
public class Task extends Thread implements HttpSessionBindingListener { public void run() { while (true) { someHeavyStuff(); if (isInterrupted()) return; } } public void valueBound(HttpSessionBindingEvent event) { start();
The first time you create and run, simply
request.getSession().setAttribute("task", new Task());
source share