I'm having an issue with WatchService. Here is a snippet of my code:
public void watch(){
//define a folder root
Path myDir = Paths.get(rootDir+"InputFiles/"+dirName+"/request");
try {
WatchService watcher = myDir.getFileSystem().newWatchService();
myDir.register(watcher, StandardWatchEventKinds.ENTRY_CREATE);
WatchKey watckKey = watcher.take();
List<WatchEvent<?>> events = watckKey.pollEvents();
for (WatchEvent event : events) {
//stuff
}
}catch(Exception e){}
watckKey.reset();
}
*First of all, know that watch() is called inside an infinite loop.
The problem is that when creating multiple files at a time, some events are missing. For example, if I copy-paste three files into the ".../request" folder, only one gets caught, the others remain as if nothing happened, neither an OVERFLOW event is triggered. In some different Computer and OS, it reaches up to two files, but if one tries 3 or more, the rest still untouched.
I found a workaround though, but I don't think it's the best practice. This is the flow:
The process starts and then stops at
WatchKey watckKey = watcher.take();
as expected, (as per Processing events). Then, I drop 3 files together in "request" folder, thus, process resumes at
List<WatchEvent<?>> events = watckKey.pollEvents();
The issue is here. It seems like the thread goes so fast through this line that two CREATED events stay behind and are lost, only one is taken. The workaround was to add an extra line right above this one, like this:
Thread.sleep(1000);
List<WatchEvent<?>> events = watckKey.pollEvents();
This seems to be a solution, at least for three and several more simultaneous files, but it's not scalable at all. So in conclusion, I would like to know if there is a better solution for this issue. FYI, I'm running a Win 7 64
Thanks a lot in advance!
Be sure to reset your watchKey. Some of the aforementioned answers don't, which could explain dropped events as well. I recommend the examples given in the official Oracle documentation: https://docs.oracle.com/javase/tutorial/essential/io/notification.html
Beware that, even when used correctly, the reliability of file services depends heavily on the underlying OS. In general, it should be considered a best-effort mechanism that doesn't give a 100% guarantee.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With