Video in progress

How do you watch for a new file appearing in a directory? How does WatchService work?

You register a directory with the WatchService and it gives you create, modify and delete events. It watches only one directory (not recursively), can lose events, and does not guarantee that a file has been written completely.

📖 Answer

WatchService ws = FileSystems.getDefault().newWatchService();
Path inbox = Path.of("/data/inbox");
inbox.register(ws, StandardWatchEventKinds.ENTRY_CREATE);

while (true) {
    WatchKey key = ws.take();                 // waits for an event
    for (WatchEvent<?> ev : key.pollEvents()) {
        if (ev.kind() == StandardWatchEventKinds.OVERFLOW) {
            rescan(inbox);                    // events were lost: rescan the directory
            continue;
        }
        Path name = (Path) ev.context();     // a relative name!
        handle(inbox.resolve(name));
    }
    if (!key.reset()) break;                  // the directory was deleted
}

Traps you meet on prod:

  • ENTRY_CREATE arrives when the file is created, not when the writing is done. A large file gets read half-written. The fix: the sender writes under a .tmp name and then does a rename, and you only pick up the final extension;
  • if you forget key.reset(), no further events arrive;
  • macOS has no native support, so the JDK polls and the events come a few seconds late;
  • on NFS and some Docker volumes, events may not arrive at all.

That is why reliable systems use WatchService only to "find out sooner", with a periodic scan running next to it.