I want to start a watchservice application while starting tomcat. I am doing this by using listener in web.xml. As expected watch service run successfully, but after that tomcat doesn't start.
watch service run successfully, but after that tomcat doesn't start. I can't access the web page Java WatchService code works in Eclipse but same code fails in Tomcat
Servlet context listeners are called in sequence on startup and exit. Yours holds up servlet initialisation thread indefinitely with an action that has while(true)
.
Fix by kicking off a background thread to handle the watch service and clean up the service thread on exit. There are different ways to do this with ExecutorService
or Thread
, here is an example listener which sets up a service thread:
public class ExampleContextListener implements ServletContextListener{
private Thread background;
private volatile boolean isRunning = true;
@Override
public void contextInitialized(ServletContextEvent sce) {
// Don't doSomeAction() here unless in background
background = new Thread(this::doSomeAction, "ExampleContextListener.doSomeAction");
background.start();
// OR Virtual thread:
// background = Thread.startVirtualThread(this::doSomeAction);
}
private void doSomeAction() {
while(isRunning) {
// Logic of your application / WatchService
}
}
@Override
public void contextDestroyed(ServletContextEvent sce) {
isRunning = false;
try {
// Wait acceptable time for clean exit
background.join(500L);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
background.interrupt();
}
}