I need to start a filewatcher service at the server start. The file watcher service starts in an infinite while loop. So I have started a thread to start the watch service in a loop by overriding the servlet init method. Now when I shutdown tomcat, this thread that is running the loop gets killed abrouptly. There is an error in tomcat logs which says that there is a memory leak issue.Is there a way to stop this thread when the server shutsdown
I have tried to override the destroy method and make while loop condition to false. But I noticed that the destroy method is not getting executed when the server shuts down.
public static void startFileWatcher() throws InterruptedException {
Runnable r = () -> {
try {
while (!exit) {
System.out.println("Exit flag: " + exit);
if (FileWatcherUtil.isFileChanged()) {
System.out.println("file is changed");
Thread.sleep(2000);
InstantiateSystemProperties.destroy();
System.out.println("Initializing new system properties");
SystemPropertiesConfigurer.loadNewXml();
InitializeLogger.resetLogger();
InstantiateSystemProperties.initializeLoggerObject();
NotificationQueue.resetQueue();
InstantiateSystemProperties.startThreadPool();
Thread.sleep(2000);
}
}
} catch (InterruptedException | IOException e) {
e.printStackTrace();
logger.error("Exception in custom init(): ", e);
}
};
Thread t = new Thread(r);
t.start();
t.setDaemon(true);
}
public static void stopThread(){
System.out.println("stopping th thread *********************************************************8");
SystemPropertiesConfigurer.exit =true;
}
Servlet destroy: @Override public void destroy() { System.out.println(".........destroy method invoked......."); InstantiateSystemProperties.destroy(); SystemPropertiesConfigurer.stopThread(); }