문제

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?

도움이 되었습니까?

해결책

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).

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top