Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WatchService: missed and unhandled events

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!

like image 271
McCoy Avatar asked Apr 22 '15 15:04

McCoy


1 Answers

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.

like image 127
user23288 Avatar answered Sep 19 '22 04:09

user23288