Java WatchService: watching directories for changes

A WatchService lets a Java program be told when files in a directory are created, changed or deleted, instead of scanning the directory again and again. This page explains what the JDK does underneath on each operating system, runs the real event sequences for common file operations, watches a whole tree, provokes an OVERFLOW, measures latency against the cost of polling, and builds a config file reloader.

Contents

How a WatchService works

A WatchService (Java 7, NIO.2) collects change notifications for directories you register. Registering a directory returns a WatchKey. When something changes, the service queues an event on that key and marks the key as signalled; your code takes signalled keys with take() or poll(), reads their events, and calls reset() to receive more. The JDK picks the mechanism from the operating system:

  • Linux: inotify. The kernel reports each change, and a JDK background thread turns the reports into events within a fraction of a millisecond.
  • Windows: ReadDirectoryChangesW, also native.
  • macOS and other systems: a polling implementation that rescans registered directories in the background, so events arrive with a delay of seconds and quick create-then-delete sequences can be missed.
WatchService building blocks
Type or memberRole
FileSystems.getDefault().newWatchService()Creates the service; close it when done
path.register(watcher, kinds...)Watches one directory, not its subdirectories
ENTRY_CREATE, ENTRY_MODIFY, ENTRY_DELETEThe event kinds you can ask for
OVERFLOWEvents were lost; always delivered, even unregistered
take(), poll(), poll(timeout, unit)Wait forever, return at once, or wait up to a timeout
key.pollEvents(), key.reset()Read the events; re-arm the key
event.context(), event.count()The file name relative to the directory; how many times it repeated
key.watchable(), key.cancel()The directory of the key; stop watching it

The events report names, not content, and never say who made a change. They are hints that something changed, after which your code looks at the file itself. All programs below were compiled and run on JDK 21 on Linux; event counts and order can differ on other systems.

Watching a directory: the real event sequence

The program watches a temporary directory while a second thread works in it, with a pause between steps. The thread creates report.txt, writes it again, renames it to final.txt, writes a file inside the subdirectory sub, and deletes final.txt.

Java
import java.io.IOException;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardWatchEventKinds;
import java.nio.file.WatchEvent;
import java.nio.file.WatchKey;
import java.nio.file.WatchService;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

public class WatchBasics {

    static void pause() {
        try {
            Thread.sleep(300);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
    }

    public static void main(String[] args) throws Exception {
        Path dir = Files.createTempDirectory("watched");
        Path sub = Files.createDirectory(dir.resolve("sub"));

        try (WatchService watcher = FileSystems.getDefault().newWatchService()) {
            dir.register(watcher, StandardWatchEventKinds.ENTRY_CREATE,
                    StandardWatchEventKinds.ENTRY_MODIFY, StandardWatchEventKinds.ENTRY_DELETE);

            // Another thread changes files while the main thread watches
            Thread.ofPlatform().start(() -> {
                try {
                    pause();
                    Files.writeString(dir.resolve("report.txt"), "v1");
                    pause();
                    Files.writeString(dir.resolve("report.txt"), "v2");
                    pause();
                    Files.move(dir.resolve("report.txt"), dir.resolve("final.txt"));
                    pause();
                    Files.writeString(sub.resolve("nested.txt"), "inside sub");
                    pause();
                    Files.delete(dir.resolve("final.txt"));
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            });

            List<String> seen = new ArrayList<>();
            WatchKey key;
            // poll with a timeout: stop when nothing has happened for 1.5 seconds
            while ((key = watcher.poll(1500, TimeUnit.MILLISECONDS)) != null) {
                for (WatchEvent<?> event : key.pollEvents()) {
                    seen.add(event.kind().name() + " " + event.context()
                            + (event.count() > 1 ? " (x" + event.count() + ")" : ""));
                }
                if (!key.reset()) {                  // false: the directory is no longer valid
                    break;
                }
            }
            seen.forEach(System.out::println);
        }
        Files.delete(sub.resolve("nested.txt"));
        Files.delete(sub);
        Files.delete(dir);
    }
}

Output on Linux (the same on every run there):

Output
ENTRY_CREATE report.txt
ENTRY_MODIFY report.txt
ENTRY_MODIFY report.txt (x2)
ENTRY_DELETE report.txt
ENTRY_CREATE final.txt
ENTRY_DELETE final.txt
  • Creating a file with content produced a CREATE and a MODIFY. The second write, which truncates and then writes, produced two MODIFY notifications, delivered as one event with count() 2. One logical change can cause several events, so react to "something changed" rather than counting events.
  • The rename appeared as DELETE of the old name and CREATE of the new one.
  • The write inside sub produced nothing. A registration covers one directory only; the next section watches a whole tree.
  • event.context() is the file name relative to the watched directory. Use dir.resolve(context) to get the full path.
  • If reset() is not called, the key stops delivering events. If it returns false, the directory was deleted or became inaccessible.

Watching a whole tree

To watch a tree, register every directory in it, keep a map from each key to its directory, and register new directories when their CREATE event arrives. The program starts with src/main, then a second thread adds a file, creates src/test, writes into it and finally deletes it again.

Java
import java.io.IOException;
import java.nio.file.FileSystems;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.StandardWatchEventKinds;
import java.nio.file.WatchEvent;
import java.nio.file.WatchKey;
import java.nio.file.WatchService;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

public class RecursiveWatch {

    static final Map<WatchKey, Path> KEYS = new HashMap<>();

    // Registers dir and every directory below it
    static void registerTree(WatchService watcher, Path dir) throws IOException {
        Files.walkFileTree(dir, new SimpleFileVisitor<>() {
            @Override
            public FileVisitResult preVisitDirectory(Path d, BasicFileAttributes attrs)
                    throws IOException {
                KEYS.put(d.register(watcher, StandardWatchEventKinds.ENTRY_CREATE,
                        StandardWatchEventKinds.ENTRY_DELETE), d);
                return FileVisitResult.CONTINUE;
            }
        });
    }

    static void pause() throws InterruptedException {
        Thread.sleep(300);
    }

    public static void main(String[] args) throws Exception {
        Path root = Files.createTempDirectory("tree");
        Files.createDirectories(root.resolve("src/main"));

        try (WatchService watcher = FileSystems.getDefault().newWatchService()) {
            registerTree(watcher, root);
            System.out.println("watched directories: " + KEYS.size());

            Thread.ofPlatform().start(() -> {
                try {
                    pause();
                    Files.writeString(root.resolve("src/main/App.java"), "class App {}");
                    pause();
                    Path added = Files.createDirectory(root.resolve("src/test"));
                    pause();                                // give the watcher time to register
                    Files.writeString(added.resolve("AppTest.java"), "class AppTest {}");
                    pause();
                    Files.delete(added.resolve("AppTest.java"));
                    Files.delete(added);
                } catch (IOException | InterruptedException e) {
                    throw new RuntimeException(e);
                }
            });

            List<String> log = new ArrayList<>();
            WatchKey key;
            while ((key = watcher.poll(1500, TimeUnit.MILLISECONDS)) != null) {
                Path dir = KEYS.get(key);
                for (WatchEvent<?> event : key.pollEvents()) {
                    Path full = dir.resolve((Path) event.context());
                    log.add(event.kind().name() + " " + root.relativize(full));
                    if (event.kind() == StandardWatchEventKinds.ENTRY_CREATE
                            && Files.isDirectory(full)) {
                        registerTree(watcher, full);        // a new directory: watch it too
                        log.add("  now watching " + root.relativize(full));
                    }
                }
                if (!key.reset()) {
                    log.add("  key for " + root.relativize(dir) + " is no longer valid");
                    KEYS.remove(key);
                }
            }
            log.forEach(System.out::println);
            System.out.println("watched directories at the end: " + KEYS.size());
        }
        Files.delete(root.resolve("src/main/App.java"));
        Files.delete(root.resolve("src/main"));
        Files.delete(root.resolve("src"));
        Files.delete(root);
    }
}

Output:

Output
watched directories: 3
ENTRY_CREATE src/main/App.java
ENTRY_CREATE src/test
  now watching src/test
ENTRY_CREATE src/test/AppTest.java
ENTRY_DELETE src/test/AppTest.java
  key for src/test is no longer valid
ENTRY_DELETE src/test
watched directories at the end: 3
  • The walk registered 3 directories: the root, src and src/main. The map turned each key back into its directory, so every event could be printed as a path from the root.
  • When src/test appeared, the program registered it, and the file written into it afterwards was reported. A file created in a new directory before it is registered is missed, which is why the writer paused here. Real code rescans a newly registered directory once to catch such files.
  • Deleting src/test invalidated its key: reset() returned false, and the program removed it from the map. The parent's DELETE event for the directory arrived on another key, so the two lines can come in either order.
  • Each watched directory uses one inotify watch. Linux limits them per user (/proc/sys/fs/inotify/max_user_watches, 63,937 on this machine), so watching a huge tree can fail with an IOException about the limit.

Bursts of changes and OVERFLOW

Events wait in the key until your code takes them. If the code is slow, the queue fills up. The program creates 2,000 files in a burst without taking any events, then reads what arrived.

Java
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardWatchEventKinds;
import java.nio.file.WatchEvent;
import java.nio.file.WatchKey;
import java.nio.file.WatchService;
import java.util.Map;
import java.util.TreeMap;
import java.util.concurrent.TimeUnit;
import java.util.stream.Stream;

public class Overflow {

    public static void main(String[] args) throws Exception {
        Path dir = Files.createTempDirectory("burst");
        try (WatchService watcher = FileSystems.getDefault().newWatchService()) {
            dir.register(watcher, StandardWatchEventKinds.ENTRY_CREATE);

            // A burst of 2,000 new files while nobody takes events
            for (int i = 0; i < 2000; i++) {
                Files.writeString(dir.resolve("f" + i + ".txt"), "x");
            }
            Thread.sleep(500);

            Map<String, Integer> kinds = new TreeMap<>();
            WatchKey key;
            while ((key = watcher.poll(500, TimeUnit.MILLISECONDS)) != null) {
                for (WatchEvent<?> e : key.pollEvents()) {
                    kinds.merge(e.kind().name(), e.count(), Integer::sum);
                }
                key.reset();
            }
            System.out.println("events received: " + kinds);

            // After OVERFLOW the only reliable answer is to look at the directory again
            if (kinds.containsKey("OVERFLOW")) {
                try (Stream<Path> s = Files.list(dir)) {
                    System.out.println("rescan after OVERFLOW finds " + s.count() + " files");
                }
            }
        }
        try (Stream<Path> s = Files.list(dir)) {
            for (Path p : s.toList()) {
                Files.delete(p);
            }
        }
        Files.delete(dir);
    }
}

Output:

Output
events received: {OVERFLOW=1488}
rescan after OVERFLOW finds 2000 files

The key held a single OVERFLOW event, with a count of 1,488, and no CREATE events at all. The JDK keeps at most 512 pending events per key; past that it discards the queue and reports one OVERFLOW whose count is the number of further changes, here the 2,000 creations minus 512. The context of an OVERFLOW event is null, so it says nothing about which files changed. The only safe reaction is the one the program takes: rescan the directory, which found all 2,000 files. Every watcher therefore needs a full-scan path anyway, and the events only make it run less often.

Latency, and what polling would cost

The alternative to a WatchService is scanning the directory on a timer. The program measures one such scan of 10,000 files, then measures how long the WatchService takes to report a write, over 20 writes.

Java
import java.io.IOException;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardWatchEventKinds;
import java.nio.file.WatchKey;
import java.nio.file.WatchService;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.Arrays;
import java.util.stream.Stream;

public class LatencyAndScanCost {

    // What a polling loop does every time: list the directory and read each file's time
    static long scan(Path dir) throws IOException {
        long newest = 0;
        try (Stream<Path> s = Files.list(dir)) {
            for (Path p : s.toList()) {
                BasicFileAttributes a = Files.readAttributes(p, BasicFileAttributes.class);
                newest = Math.max(newest, a.lastModifiedTime().toMillis());
            }
        }
        return newest;
    }

    public static void main(String[] args) throws Exception {
        Path dir = Files.createTempDirectory("latency");
        for (int i = 0; i < 10000; i++) {
            Files.writeString(dir.resolve("file-" + i + ".dat"), "x");
        }

        long best = Long.MAX_VALUE;
        for (int i = 0; i < 3; i++) {
            long start = System.nanoTime();
            scan(dir);
            best = Math.min(best, System.nanoTime() - start);
        }
        System.out.printf("one polling scan of 10,000 files: %.1f ms (best of 3)%n", best / 1e6);
        System.out.printf("scanning once per second costs about %.0f s of CPU per hour%n",
                best / 1e9 * 3600);

        // How long from a write until the WatchService reports it
        try (WatchService watcher = FileSystems.getDefault().newWatchService()) {
            dir.register(watcher, StandardWatchEventKinds.ENTRY_MODIFY);
            long[] micros = new long[20];
            for (int i = 0; i < micros.length; i++) {
                long start = System.nanoTime();
                Files.writeString(dir.resolve("file-" + i + ".dat"), "changed " + i);
                WatchKey key = watcher.take();
                micros[i] = (System.nanoTime() - start) / 1000;
                key.pollEvents();
                key.reset();
            }
            Arrays.sort(micros);
            System.out.printf("write-to-event delay over 20 writes: median %.1f ms, max %.1f ms%n",
                    micros[10] / 1e3, micros[19] / 1e3);
        }

        try (Stream<Path> s = Files.list(dir)) {
            for (Path p : s.toList()) {
                Files.delete(p);
            }
        }
        Files.delete(dir);
    }
}

Output (rough comparison on a 2-CPU Linux VM, JDK 21; absolute times will differ on yours):

Output
one polling scan of 10,000 files: 16.4 ms (best of 3)
scanning once per second costs about 59 s of CPU per hour
write-to-event delay over 20 writes: median 0.1 ms, max 3.3 ms
  • A single scan of 10,000 files took between about 10 and 30 ms in repeated runs. Done once per second, that adds up to tens of seconds or more of CPU per hour, as the second line shows, for a directory where nothing may change, and a change is still noticed up to a second late.
  • The WatchService reported a write within a fraction of a millisecond in the median case, and in a few milliseconds at worst, while using no CPU between changes.
  • On macOS, where the JDK itself polls, the latency is seconds rather than milliseconds, and the CPU cost of scanning is paid by the JDK's background thread instead.

A config file reloader

A common use is reloading configuration when its file changes. The program loads app.properties, then a background thread changes the log level twice: once by writing the file directly, and once by writing a temporary file and moving it over the original atomically, as careful editors and deployment tools do.

Java
import java.io.IOException;
import java.io.Reader;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.nio.file.StandardWatchEventKinds;
import java.nio.file.WatchEvent;
import java.nio.file.WatchKey;
import java.nio.file.WatchService;
import java.util.Properties;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;

public class ConfigReloader {

    static final AtomicReference<Properties> CONFIG = new AtomicReference<>(new Properties());

    static void load(Path file) throws IOException {
        Properties p = new Properties();
        try (Reader r = Files.newBufferedReader(file)) {
            p.load(r);
        }
        CONFIG.set(p);                               // readers always see a complete config
        System.out.println("loaded: level=" + p.getProperty("log.level"));
    }

    public static void main(String[] args) throws Exception {
        Path dir = Files.createTempDirectory("config");
        Path file = dir.resolve("app.properties");
        Files.writeString(file, "log.level=INFO\n");
        load(file);

        // Edit the file twice in the background, the second time by atomic replacement
        Thread.ofPlatform().start(() -> {
            try {
                Thread.sleep(400);
                Files.writeString(file, "log.level=DEBUG\n");
                Thread.sleep(800);
                Path tmp = Files.writeString(dir.resolve("app.properties.tmp"), "log.level=WARN\n");
                Files.move(tmp, file, StandardCopyOption.REPLACE_EXISTING,
                        StandardCopyOption.ATOMIC_MOVE);
            } catch (IOException | InterruptedException e) {
                throw new RuntimeException(e);
            }
        });

        try (WatchService watcher = FileSystems.getDefault().newWatchService()) {
            // Watch the directory, not the file: atomic replacement creates a new file
            dir.register(watcher, StandardWatchEventKinds.ENTRY_MODIFY,
                    StandardWatchEventKinds.ENTRY_CREATE);
            WatchKey key;
            while ((key = watcher.poll(2, TimeUnit.SECONDS)) != null) {
                boolean changed = false;
                for (WatchEvent<?> e : key.pollEvents()) {
                    changed |= file.getFileName().equals(e.context());
                }
                key.reset();
                if (changed) {
                    Thread.sleep(100);               // debounce: let the writer finish
                    key.pollEvents();
                    load(file);
                }
            }
        }
        System.out.println("final level: " + CONFIG.get().getProperty("log.level"));
        Files.delete(file);
        Files.delete(dir);
    }
}

Output:

Output
loaded: level=INFO
loaded: level=DEBUG
loaded: level=WARN
final level: WARN

Both changes were picked up, each with one reload. Design points:

  • Watch the directory, not the file: a WatchService can only register directories, and the atomic replacement creates a new file under the same name, which a watch on the old file would miss. Filtering events by file name keeps only the relevant ones.
  • Debounce: one save can produce several events, and a reader can catch the file half-written. Waiting 100 ms and draining the extra events means one reload per change.
  • Publish atomically: the new Properties is loaded completely and then swapped in with an AtomicReference, so other threads never see a partly loaded configuration. For the file format, see properties files.
  • Keep the old configuration when a reload fails, for example because the new file has a syntax error, and log the problem instead of crashing.

For writing files safely with a temporary file and an atomic move, see writing a text file.

Running and stopping the watch loop

A watch loop usually blocks in take() on its own thread, so the program needs a way to stop it and to stop watching single directories. The program runs the loop on a virtual thread, cancels a key, and then closes the service while the loop is blocked.

Java
import java.nio.file.ClosedWatchServiceException;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardWatchEventKinds;
import java.nio.file.WatchKey;
import java.nio.file.WatchService;
import java.util.concurrent.CountDownLatch;

public class Lifecycle {

    public static void main(String[] args) throws Exception {
        Path dir = Files.createTempDirectory("lifecycle");
        WatchService watcher = FileSystems.getDefault().newWatchService();
        WatchKey key = dir.register(watcher, StandardWatchEventKinds.ENTRY_CREATE);
        System.out.println("key valid: " + key.isValid() + ", watches "
                + dir.equals(key.watchable()));

        // The watching loop runs on a virtual thread: take() blocks without using a carrier
        CountDownLatch stopped = new CountDownLatch(1);
        Thread loop = Thread.ofVirtual().start(() -> {
            try {
                while (true) {
                    WatchKey k = watcher.take();
                    k.pollEvents().forEach(e -> System.out.println("event: " + e.kind().name()
                            + " " + e.context()));
                    k.reset();
                }
            } catch (ClosedWatchServiceException e) {
                System.out.println("take() ended with ClosedWatchServiceException");
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            } finally {
                stopped.countDown();
            }
        });

        Files.writeString(dir.resolve("a.txt"), "a");
        Thread.sleep(300);

        key.cancel();                                       // stop watching this directory
        System.out.println("after cancel: key valid " + key.isValid());
        Files.writeString(dir.resolve("b.txt"), "b");       // no event for this one
        Thread.sleep(300);

        watcher.close();                                    // wakes the blocked take()
        stopped.await();
        System.out.println("loop thread finished: " + !loop.isAlive());

        Files.delete(dir.resolve("a.txt"));
        Files.delete(dir.resolve("b.txt"));
        Files.delete(dir);
    }
}

Output:

Output
key valid: true, watches true
event: ENTRY_CREATE a.txt
after cancel: key valid false
take() ended with ClosedWatchServiceException
loop thread finished: true
  • key.watchable() returned the registered directory, and the loop reported the creation of a.txt.
  • After key.cancel() the key was invalid, and creating b.txt produced no event. Cancelling is how a tree watcher stops watching a directory it no longer cares about.
  • watcher.close() from the main thread woke the blocked take(), which threw ClosedWatchServiceException, and the loop ended cleanly. This is the usual shutdown path, for example from a shutdown hook. Interrupting the thread also works, with InterruptedException.
  • take() waits on a queue, so on a virtual thread it parks without holding an operating system thread. One virtual thread per watched area is cheap.

When to use a WatchService

Choosing how to detect file changes
SituationApproach
React quickly to changes in one directoryWatchService with take() on a dedicated thread
A whole treeRegister every directory and each new one on CREATE, with a rescan of new directories
Reload one configuration fileWatch its directory, filter by name, debounce, swap atomically
Bursts of many changesHandle OVERFLOW with a full rescan
Network file systems such as NFS or SMBPolling: change notifications often do not work for changes made by other machines
Changes that happened while the program was not runningCompare a stored scan with a fresh one; events are never replayed
Need to know the new contentRead the file after the event; events carry only names

For scanning directories efficiently when you do need to poll, see Files.walk and walkFileTree.