I have an ExecutorService that is running a WatchService to monitor when files are changed in a directory and then save a copy of that file. I start the ExecutorService when Tomcat starts using the ServletContextListener. This code works great for several days but then eventually the code quits working with no errors in Tomcat log. Does anyone know why this might be stopping or even how I could monitor when it does stop and restart it without having to restart Tomcat? Below is the code I am using.
import java.io.File;
import java.io.IOException;
import java.nio.file.CopyOption;
import java.nio.file.FileSystem;
import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.nio.file.StandardWatchEventKinds;
import java.nio.file.WatchEvent;
import java.nio.file.WatchKey;
import java.nio.file.WatchService;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
public class BackupServlet implements ServletContextListener {
private static String uiFolderPath = "C:\\.......\\custom\\";
private final static CopyOption[] options = new CopyOption[]{
StandardCopyOption.REPLACE_EXISTING,
StandardCopyOption.COPY_ATTRIBUTES
};
private ExecutorService executor;
private WatchService watcher;
private FileSystem fs = FileSystems.getDefault();
public void contextInitialized(ServletContextEvent contextEvent) {
try {
String folderPath = uiFolderPath + "backups\\updates";
createFolder(folderPath);
watcher = fs.newWatchService();
Path path = Paths.get(uiFolderPath);
WatchKey key = path.register(watcher, StandardWatchEventKinds.ENTRY_MODIFY);
executor = Executors.newSingleThreadExecutor();
startWatching();
} catch (IOException e) {
e.printStackTrace();
}
}
public void contextDestroyed(ServletContextEvent contextEvent) {
executor.shutdownNow();
}
private void startWatching() {
executor.submit(new Runnable() {
@Override
public void run() {
try {
WatchKey key;
while ((key = watcher.take()) != null) {
Thread.sleep(100);
List<WatchEvent<?>> events = key.pollEvents();
for (WatchEvent<?> event : events) {
String fileName = event.context().toString();
if (fileName.endsWith(".json")) {
//save backup version of file modified
}
}
key.reset();
}
} catch (Exception ex) {
Utilities.writeLog("Error backing up files", ex.toString());
}
}
});
}
private File createFolder(String folderPath) {
File folder = new File(folderPath);
if (!folder.exists())
folder.mkdir();
return folder;
}
}