How to correctly recover when WatchKey.reset() returns false?

Viewed 1164

I have a long running process that 'watches' a directory for file changes.

The new Java 8 'watcher' API makes it very clear that WatchKey.reset() must be called on references returned by WatchService.take(). Note: The return result from WatchKey.reset() matches WatchKey.isValid().

Yesterday, my long running process observed many file updates and WatchKey.reset() normally returned true. However, for reasons I do not understand, a one call to WatchKey.reset() returned false.

  1. What is the meaning of return value false from WatchKey.reset()? The official tutorial says: "If the key is no longer valid, the directory is inaccessible so exit the loop."
  2. How do I recover from this state? I wish to continue monitoring the directory for file changes. The official tutorial and documentation does not explain how to do this.

For those less familiar with this new API, here is some setup code:

public static void main(String[] argArr)
throws IOException, InterruptedException {

    final File dirPath = new File(argArr[0]);
    if (! dirPath.isDirectory()) {
        throw new IllegalArgumentException(argArr[0]);
    }
    final Path dirPath2 = dirPath.toPath();
    try (final WatchService watchService = FileSystems.getDefault().newWatchService()) {

        final WatchKey registerWatchKey =
            dirPath2.register(
                watchService,
                StandardWatchEventKinds.ENTRY_CREATE,
                StandardWatchEventKinds.ENTRY_MODIFY,
                StandardWatchEventKinds.ENTRY_DELETE);

        try {
            while (true) {
                // blocking
                final WatchKey watchKey = watchService.take();
                final List<WatchEvent<?>> watchEventList = watchKey.pollEvents();
                for (final WatchEvent<?> watchEvent : watchEventList) {
                    // use 'watchEvent'
                }
                final boolean isValid = watchKey.reset();
                if (! isValid) {
                    // How to recover here?  I want to continue monitoring dirPath2.
                }
            }
        }
        finally {
            registerWatchKey.cancel();
        }
    }
}
0 Answers
Related