简体   繁体   中英

How to handle the JAVA WatchService Overflow event?

I want to detect the Creation and Modification of files using JAVA. I am using the WatchService API provided by JDK 7.

So, when there is multiple file creation at a given instance there is a level that the watch service can handle and then it generates and OVERFLOW event.

Sample code part is provided below.

What is the most suitable way to handle that situation when there is and overflow event thrown in order to detect the creation of all the files?

for (WatchEvent<?> event : key.pollEvents()) {
    WatchEvent.Kind kind = event.kind();
    // TBD - provide example of how OVERFLOW event is handled
    if (kind == OVERFLOW) {
         System.err.println("OVERFLOW !");
         continue;
    }
}

Hopefully, you have already found a solution for this. Usually the idea is to process newly created files and move the processed files to a different directory.

There are two possible options to deal with this:

  • Prevent OVERFLOW from occurring
  • Handle OVERFLOW if it has still occurred

Prevent OVERFLOW from occurring The idea is to clear the Operating System buffer quickly and populating a queue with the event information and then having multiple threads process the events in the queue.

Handle OVERFLOW if it has still occurred

If the OVERFLOW still occurs,

  • stop listening to events
  • clear the queue
  • call listFiles() on the directory
  • start listening to events again
  • insert the listed files in the queue

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM