Scrivio Interview library
CodingFoundations6 min read · updated 12 November 2026

Write code that watches a directory for new files using WatchService and processes each one. What are common mistakes?

We create a WatchService, register the directory with dir.register(watcher, ENTRY_CREATE), and loop on watcher.take(), which blocks until a key has events. For each event we resolve its context, a path relative to the directory, against the directory, process the file, and then call key.reset(), stopping if it returns false because the key is no longer valid. Common mistakes are forgetting reset(), ignoring the OVERFLOW event that signals lost events, processing a file before its writer has finished, and expecting the watch to cover subdirectories, which it does not.

Why this question is asked

Watching a directory for new files is a common integration pattern: another system drops CSV files, images or reports into an inbox, and our service picks them up. WatchService makes the basic version short, but it has a particular protocol around keys and events, and getting it slightly wrong produces a watcher that stops after the first file, misses files under load or reads half-written files. Interviewers ask for the code and the mistakes together to see whether we know the protocol and the real-world behaviour of file systems. In this answer, we will recap how WatchService works, write a complete watcher, then go through each common mistake and how the code handles it.

1A Quick Recap of WatchService

WatchService, part of java.nio.file since Java 7, delivers notifications when entries in a directory change. We obtain one from the file system, register directories with it, and say which kinds of events we care about: ENTRY_CREATE, ENTRY_MODIFY and ENTRY_DELETE. Registering returns a WatchKey, a token that represents that directory's registration.

A key has a simple lifecycle. It starts ready. When events happen in its directory, the key is signalled and queued in the watch service. We retrieve it with take(), which blocks, or poll(), which does not, and read its pending events with pollEvents(). While we process them, the key is not queued again, even if new events arrive; they accumulate on the key. Calling reset() returns the key to the ready state so it can be signalled again. Each event has a kind and a context, which for directory events is the relative Path of the entry that changed.

Step throughThe watch loop
  1. key = watcher.take()blocks until some directory has events
  2. For each event in key.pollEvents()
  3. Is the kind OVERFLOW?
    Yesrescan the whole directoryNoresolve the context against the directory and process the file
  4. key.reset() returned true?
    Yesback to take()Nodirectory is gone: stop or re-register

4 steps in order. Play them, or step through them one at a time.

2A Complete Watcher

Here is a watcher for an inbox directory. It handles creation events, overflow, and invalid keys, and it processes each file only when it is complete.

Java
import static java.nio.file.StandardWatchEventKinds.*;
void watch(Path dir) throws IOException, InterruptedException {
try (WatchService watcher = dir.getFileSystem().newWatchService()) {
dir.register(watcher, ENTRY_CREATE);
scanExisting(dir); // files that arrived before we started
while (true) {
WatchKey key = watcher.take(); // blocks
for (WatchEvent<?> event : key.pollEvents()) {
if (event.kind() == OVERFLOW) { // events were lost
scanExisting(dir);
continue;
}
Path name = (Path) event.context(); // relative: "orders-0412.csv"
Path file = dir.resolve(name); // absolute: /data/inbox/orders-0412.csv
if (file.toString().endsWith(".csv")) process(file);
}
if (!key.reset()) break; // directory deleted or inaccessible
}
}
}
void scanExisting(Path dir) throws IOException {
try (Stream<Path> files = Files.list(dir)) {
files.filter(p -> p.toString().endsWith(".csv")).forEach(this::process);
}
}

Notice the order of steps and the reason for each. We register before scanning the existing files, so a file arriving between the two is either in the scan or produces an event; it can be seen twice, which is why process must be idempotent, for example by moving each file to a done folder once handled. We resolve the event's context against the directory, because the context is only the file name. And we call reset() after every key, outside the event loop.

3Mistake 1: Forgetting reset()

If we do not call key.reset(), the key is never queued again. The watcher processes the first batch of events and then take() blocks forever, while files pile up in the directory. It is an especially confusing bug because the first test, with a single file, passes. Checking the return value matters as well: reset() returns false when the key is no longer valid, for example because the directory was deleted or the watch service was closed, and looping on an invalid key would wait forever.

4Mistake 2: Ignoring OVERFLOW

The operating system keeps a limited queue of events. If many files arrive faster than we handle them, for example a batch of 50,000 files copied in at once, the queue fills and further events are dropped. WatchService then delivers an event of kind OVERFLOW, whose context is null. Code that casts every context to Path fails with a NullPointerException there, and code that skips the event silently misses files. The correct response, as in our code, is to treat OVERFLOW as I do not know what changed and rescan the directory.

5Mistake 3: Processing a File Before It Is Complete

ENTRY_CREATE fires when the directory entry appears, which is when the writer opens the file, not when it finishes writing. If we process immediately, we can read an empty or partial file. Waiting for ENTRY_MODIFY events to stop is unreliable, since a slow writer can pause. The robust solution is a convention with the producer. The best one is to write to a temporary name or another directory and rename into the inbox when done, since a rename within one file system is atomic; we then ignore names such as *.tmp and only see complete files. Another is a marker file, such as orders-0412.csv.done, written after the data file. When we cannot change the producer, we can wait until the file's size and modification time have been stable for a few seconds, which is a heuristic, not a guarantee.

6Mistake 4: Expecting Subdirectories to Be Watched

Registering a directory watches only its direct entries. Creating inbox/2026/11/report.csv produces at most an ENTRY_CREATE for inbox/2026 and nothing for the file deep inside. To watch a tree we must register every subdirectory, typically by walking the tree at startup with Files.walk and registering each directory, and then registering new directories as their ENTRY_CREATE events arrive, scanning them immediately because files may already have been created inside before we registered. We keep a map from each WatchKey to its directory, because the event context is relative to that key's directory, not to the root.

Java
Map<WatchKey, Path> dirs = new HashMap<>();
void registerTree(Path root, WatchService w) throws IOException {
try (Stream<Path> all = Files.walk(root)) {
for (Path d : all.filter(Files::isDirectory).toList()) {
dirs.put(d.register(w, ENTRY_CREATE), d); // key -> its directory
}
}
}

7Follow-up questions

Should process() run on the watcher thread?

Usually not for slow work. While the watcher thread is busy, events pile up and the operating system queue can overflow. A common design is for the watcher thread only to put file paths on a queue, and a pool of workers, or virtual threads, to do the processing. The watcher stays responsive and overflow becomes rare.

How do you stop the watcher cleanly?

Close the WatchService from another thread, for example in a shutdown hook or a Spring @PreDestroy method. A thread blocked in take() then gets a ClosedWatchServiceException, and an interrupted thread gets InterruptedException; either way the loop ends and try-with-resources releases the native resources.

8Conclusion

In this answer, we wrote a WatchService loop that registers the directory for ENTRY_CREATE, scans existing files, blocks on take(), resolves each event's relative context against the directory, and calls reset() after every key, stopping when it returns false. We saw the common mistakes: a missing reset() that stops the watcher, ignoring OVERFLOW, which means events were lost, processing files that are still being written, which a rename convention solves, and expecting recursion, which requires registering each subdirectory ourselves.

What to say in the interviewAbout 90 seconds aloud

Open with

I would create a WatchService from the directory's file system, call dir.register(watcher, ENTRY_CREATE), and then loop on watcher.take(), which blocks until a key is signalled. For each event in key.pollEvents() I check the kind.

Then, if they want more

If it is OVERFLOW, it means the OS dropped events, so I rescan the whole directory. Otherwise the context is a relative path, just the file name, so I resolve it against the directory before processing.

After the events I call key.reset(), and if it returns false the key is invalid, usually because the directory is gone, so I stop or re-register. Before the loop I register first and then scan existing files, so nothing that arrived before startup is missed, and I make processing idempotent because a file can be seen twice.

The common mistakes: forgetting reset, so the watcher works once and then never wakes up again; ignoring OVERFLOW, or casting its null context; processing on ENTRY_CREATE while the producer is still writing, which I solve by agreeing that the producer writes to a temp name and renames into the directory, or writes a done marker; and assuming WatchService is recursive.

It only watches direct entries, so for a tree I register each subdirectory, including new ones as they are created, and keep a map from key to directory. I would also hand slow processing to worker threads so the watcher keeps up.

About this answer

Last updated
12 November 2026
Versions it names
Java 7
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "Write code that watches a directory for new files using WatchService and processes each...": https://scrivio-interview-library.netlify.app/java/io-and-nio/0b0d2caa6f/