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 WatchServiceWatchKeytake()poll()reset()
- Linux: inotify. The kernel reports each change, and a JDK background thread turns the reports into events within a fraction of a millisecond.
- Windows:
, also native.ReadDirectoryChangesW - 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.
| Type or member | Role |
|---|---|
FileSystems.getDefault().newWatchService() | Creates the service; close it when done |
path.register(watcher, kinds...) | Watches one directory, not its subdirectories |
ENTRY_CREATEENTRY_MODIFYENTRY_DELETE | The event kinds you can ask for |
OVERFLOW | Events 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.txtfinal.txtsubfinal.txt
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):
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
and aCREATE . The second write, which truncates and then writes, produced twoMODIFY notifications, delivered as one event withMODIFY 2. One logical change can cause several events, so react to "something changed" rather than counting events.count() - The rename appeared as
of the old name andDELETE of the new one.CREATE - The write inside
produced nothing. A registration covers one directory only; the next section watches a whole tree.sub is the file name relative to the watched directory. Useevent.context() to get the full path.dir.resolve(context)- If
is not called, the key stops delivering events. If it returnsreset() , the directory was deleted or became inaccessible.false
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 CREATEsrc/mainsrc/test
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:
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,
andsrc . The map turned each key back into its directory, so every event could be printed as a path from the root.src/main - When
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.src/test - Deleting
invalidated its key:src/test returnedreset() , and the program removed it from the map. The parent'sfalse event for the directory arrived on another key, so the two lines can come in either order.DELETE - Each watched directory uses one inotify watch. Linux limits them per user (
, 63,937 on this machine), so watching a huge tree can fail with an/proc/sys/fs/inotify/max_user_watches about the limit.IOException
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.
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:
events received: {OVERFLOW=1488}
rescan after OVERFLOW finds 2000 files
The key held a single OVERFLOWCREATEOVERFLOWOVERFLOWnull
Latency, and what polling would cost
The alternative to a WatchServiceWatchService
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):
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
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.WatchService - 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
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:
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
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.WatchService - 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
is loaded completely and then swapped in with anProperties , so other threads never see a partly loaded configuration. For the file format, seeAtomicReferenceproperties 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
Running and stopping the watch loop
A watch loop usually blocks in take()
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:
key valid: true, watches true
event: ENTRY_CREATE a.txt
after cancel: key valid false
take() ended with ClosedWatchServiceException
loop thread finished: true
returned the registered directory, and the loop reported the creation ofkey.watchable() .a.txt- After
the key was invalid, and creatingkey.cancel() produced no event. Cancelling is how a tree watcher stops watching a directory it no longer cares about.b.txt from the main thread woke the blockedwatcher.close() , which threwtake() , and the loop ended cleanly. This is the usual shutdown path, for example from a shutdown hook. Interrupting the thread also works, withClosedWatchServiceException .InterruptedException waits on a queue, so on atake()virtual thread it parks without holding an operating system thread. One virtual thread per watched area is cheap.
When to use a WatchService
| Situation | Approach |
|---|---|
| React quickly to changes in one directory | WatchServicetake() |
| A whole tree | Register every directory and each new one on CREATE |
| Reload one configuration file | Watch its directory, filter by name, debounce, swap atomically |
| Bursts of many changes | Handle OVERFLOW |
| Network file systems such as NFS or SMB | Polling: change notifications often do not work for changes made by other machines |
| Changes that happened while the program was not running | Compare a stored scan with a fresh one; events are never replayed |
| Need to know the new content | Read the file after the event; events carry only names |
For scanning directories efficiently when you do need to poll, see