1

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?

4

1 回答 1

0

老实说,这是确保您仍在处理此 WatchKey/Path 映射的事件的最简单方法。

如果队列中的同一个文件有两个事件。在处理事件 #1 时,您决定停止处理此路径的事件。

之后,您从 WatchService 检索下一个键(与事件 #1 相同的路径),您可以立即忽略它(continue)。

于 2014-05-13T10:57:52.970 回答