Course contentsShow
← Java
Lesson 2101 of 2,87041. NIO.2 and the Path APIFree lesson

Handling Watch Service in a Monitoring Loop

Implementing a typical monitoring loop with take(), pollEvents(), and reset() for continuous file watching.

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:

  1. take() - Blocks until a WatchKey signals that events occurred
  2. pollEvents() - Retrieves all events from that key
  3. reset() - 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!