Question

I'm learning about file watchers in nio2, and an example file had a Map variable where they mapped files to watch keys, and had the following code:

            for (;;) {

                // wait for key to be signaled
                WatchKey key;
                try {
                   key = watcher.take();
                } catch (InterruptedException x) {
                   return;
                }

                Path dir = keys.get(key);
                if (dir == null) {
                    System.err.println("WatchKey not recognized!!");
                    continue;
                }
                (...)
            }

According to this example, i'm led to believe that the watch service occasionally might give me a false-positive (a key that's not mapped to a file the application is watching), but in the Oracle Reference they make no such check. I'm now unsure whether i really need have the dictionary or not. Can anyone with experience with nio2 shed some light on this?

Était-ce utile?

La solution

In my honest opinion this is the simplest way to assure, that you're still handling events for this WatchKey/Path mapping.

In case there are two events for the same file in the queue. While handling event #1 you decide to stop handling events for this Path.

After that you retrieve the next key from the WatchService (same Path as event #1), you are immediately able to ignore it (continue).

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top