Resetting the WatchKey for Continued Monitoring
You'll learn how to keep your WatchService actively monitoring by properly resetting WatchKeys after processing their events.
When you process events from a WatchKey, that key becomes inactive—it won't signal new events until you explicitly reset it. Think of a WatchKey like a notification bell: once it rings and you check it, you must reset the bell so it can ring again for future events.
The reset() Method
After calling pollEvents() and processing the events, you must call reset() on the WatchKey:
WatchKey key = watchService.poll();
if (key != null) {
for (WatchEvent<?> event : key.pollEvents()) {
// Process each event
System.out.println("Event: " + event.kind());
}
// Critical: reset the key to continue monitoring
boolean valid = key.reset();
if (!valid) {
System.out.println("WatchKey no longer valid");
break; // Stop monitoring
}
}
Understanding Key Invalidation
The reset() method returns a boolean:
true: The key is still valid and will continue monitoringfalse: The key is invalid (directory deleted, watch service closed, etc.)
When a key becomes invalid, it will never become valid again—you must stop using it. This prevents your monitoring loop from attempting to watch nonexistent directories or continuing after deliberate shutdown.
Always check the return value of reset() in long-running monitoring loops. Without it, your application might continue running but silently stop receiving notifications.
Key Takeaway: Always call WatchKey.reset() after processing events to re-enable monitoring, and check its boolean return value to detect key invalidation and gracefully stop monitoring when necessary.