I need to monitor changes( uploaded files ) in two directories in a web application. I created a ServletContextListener that triggers the monitoring of these two directories.
My problem is that when the first monitoring starts, the thread is blocked and the second monitoring does not start.
Is possible to keep the monitoring of two different folders running in parallel and background?
I know that the problem is due to an infinite loop , but do not know how to put this thread in the background. Any help will be appreciated . Thank you very much in advance
ContextListener
@Override
public void contextInitialized(ServletContextEvent event) {
Path pathFolder1 = Paths.get("my_folder_1_path");
MyWatcher watcher1 = new MyWatcher();
Path pathFolder2 = Paths.get("my_folder_2_path");
MyWatcher watcher2 = new MyWatcher();
watcher1.startMonitoring(pathFolder1);
watcher2.startMonitoring(pathFolder2);
}
MyWatcher
public void startMonitoring(Path directory) {
try {
FileSystem fs = directory.getFileSystem ();
WatchService watcher = fs.newWatchService();
while(true) {
directory.register(watcher, StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_DELETE);
WatchKey watckKey = watcher.take();
List<WatchEvent<?>> events = watckKey.pollEvents();
for (WatchEvent event : events) {
if (event.kind() == StandardWatchEventKinds.ENTRY_CREATE) {
System.out.println("File created: " + event.context().toString());
}
if (event.kind() == StandardWatchEventKinds.ENTRY_DELETE) {
System.out.println("File removed: " + event.context().toString());
}
}
watckKey.reset();
}
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
You should configure a thread factory on the app server, inject it through a @Resource annotation, and use threads from there. An googled example would be a blog entry about this.