Events missed while using Watch Service in Java NIO

46 views Asked by At

I was reading up on Java NIO, specifically on WatchService. And I found this snippet of code:

WatchKey key;
while ((key = watchService.take()) != null) {
    for (WatchEvent<?> event : key.pollEvents()) {
        //process
    }
    key.reset();
}

Now, as we know, take API is a blocking call, which returns null or the WatchKey when any registered StandardWatchEventKinds occurs. And once we get the key back, it is not queued back again to watch for events until we call the reset API.

Now going back to the code snippet, if we have an event, the key will be returned and we will enter the for loop. Now if the processing logic is time consuming, since the key is already returned we are not watching for any new events. Only when we exit the for loop and call the reset API we start watching again. This could result in some missed events.

Is my assessment correct, or am I missing something here?

0

There are 0 answers