Handling Watch Service in a Monitoring Loop
What you'll learn: How to structure a continuous monitoring loop that watches for file system changes using WatchService.
Now that you understand individual pieces—creating a WatchService, registering paths, and processing events—it's time to put them together into a complete monitoring loop that runs continuously.
The Monitoring Loop Pattern
Think of a security guard watching multiple surveillance monitors. They wait for an alert (take()), review what triggered it (pollEvents()), handle the situation, then reset the system to watch again (reset()). Your monitoring loop follows this exact pattern.
The typical structure uses an infinite loop with three key steps:
take()- Blocks until aWatchKeysignals that events occurredpollEvents()- Retrieves all events from that keyreset()- Resets the key so it can detect future events
The Standard Pattern
WatchService watchService = FileSystems.getDefault().newWatchService();
Path dir = Paths.get("documents");
dir.register(watchService, StandardWatchEventKinds.ENTRY_CREATE,
StandardWatchEventKinds.ENTRY_MODIFY);
while (true) {
WatchKey key = watchService.take(); // Blocks until events occur
for (WatchEvent<?> event : key.pollEvents()) {
WatchEvent.Kind<?> kind = event.kind();
Path filename = (Path) event.context();
System.out.println(kind.name() + ": " + filename);
}
if (!key.reset()) {
System.out.println("Key no longer valid");
break; // Directory became inaccessible
}
}
Critical: If reset() returns false, the key is no longer valid (perhaps the directory was deleted), and you should stop monitoring or handle the error appropriately.
Key Takeaway: A typical WatchService monitoring loop continuously calls take() to wait for events, pollEvents() to process them, and reset() to rearm the watch key—forgetting reset() means you'll only detect changes once!