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

The WatchKey and Polling for Events

Using take() and poll() methods on WatchService to retrieve WatchKeys representing directory changes.

The WatchKey and Polling for Events

What you'll learn: How to retrieve and process file system change notifications using WatchKey objects and polling methods on WatchService.

Understanding the WatchKey

Once you've registered a directory with a WatchService, the service doesn't immediately notify you of changes. Instead, it queues up WatchKey objects that represent detected events. Think of WatchKey as a ticket claiming "something happened in this directory." To process these tickets, you need to actively retrieve them from the queue.

Polling Methods: take() and poll()

The WatchService provides two primary methods for retrieving WatchKeys:

take()

This method blocks (waits) until an event occurs. Your program will pause at this line until the WatchService has a WatchKey ready to deliver. It's like waiting at a help desk—you stand there until a representative becomes available.

WatchKey key = watchService.take(); // Waits indefinitely

poll()

This method returns immediately, giving you either a WatchKey (if one is available) or null (if the queue is empty). You can also use an overloaded version with a timeout.

WatchKey key = watchService.poll(); // Returns null if nothing ready
// Or with timeout:
WatchKey key = watchService.poll(5, TimeUnit.SECONDS); // Waits up to 5 seconds

Choosing Your Approach

Use take() when you want a dedicated monitoring thread that responds to changes as they happen. Use poll() when you want to check for events periodically without blocking, or when you need timeout control.

Key Takeaway: The WatchKey represents queued file system events, retrieved from WatchService using take() (blocking) or poll() (non-blocking/timeout-based) methods to process directory changes.