Course – LS – All

Get started with Spring and Spring Boot, through the Learn Spring course:

>> CHECK OUT THE COURSE

1. Overview

In this article, we are going to explore the WatchService interface of Java NIO.2 filesystem APIs. This is one of the lesser known features of the newer IO APIs that were introduced in Java 7 alongside FileVisitor interface.

To use the WatchService interface in your applications, you need to import the appropriate classes:

import java.nio.file.*;

2. Why Use WatchService

A common example to understand what the service does is actually the IDE.

You might have noticed that the IDEs always detects a change in source code files that happen outside itself. Some IDE’s inform you using a dialog box so that you can choose to reload the file from the filesystem or not, others simply update the file in the background.

Similarly, newer frameworks such as Play also does hot reloading of the application code by default – whenever you’re performing edits from any editor.

These applications employ a feature called file change notification that is available in all filesystems.

Basically, we can write code to poll the filesystem for changes on specific files and directories. However, this solution is not scalable especially if the files and directories reach the hundreds and thousands.

In Java 7 NIO.2, the WatchService API provides a scalable solution for monitoring directories for changes. It has a clean API and is so well optimized for performance that we don’t need to implement our own solution.

3. How Does the Watchservice Work?

To use the WatchService features, the first step is to create a WatchService instance using the java.nio.file.FileSystems class:

WatchService watchService = FileSystems.getDefault().newWatchService();

Next, we have to create the path to the directory we want to monitor:

Path path = Paths.get("pathToDir");

After this step, we have to register the path with watch service. There are two important concepts to understand at this stage. The StandardWatchEventKinds class and the WatchKey class. Take a look at the following registration code just to understand where each fall. We will follow this with explanations of the same:

WatchKey watchKey = path.register(
  watchService, StandardWatchEventKinds...);

Notice only two important things here: First, the path registration API call takes the watch service instance as the first parameter followed by variable arguments of StandardWatchEventKinds. Secondly, the return type of the registration process is a WatchKey instance.

3.1. The StandardWatchEventKinds

This is a class whose instances tell the watch service the kinds of events to watch for on the registered directory. There are currently four possible events to watch for:

  • StandardWatchEventKinds.ENTRY_CREATE – triggered when a new entry is made in the watched directory. It could be due to the creation of a new file or renaming of an existing file.
  • StandardWatchEventKinds.ENTRY_MODIFY – triggered when an existing entry in the watched directory is modified. All file edit’s trigger this event. On some platforms, even changing file attributes will trigger it.
  • StandardWatchEventKinds.ENTRY_DELETE – triggered when an entry is deleted, moved or renamed in the watched directory.
  • StandardWatchEventKinds.OVERFLOW – triggered to indicate lost or discarded events. We won’t focus much on it

3.2. The WatchKey

This class represents the registration of a directory with the watch service. Its instance is returned to us by the watch service when we register a directory and when we ask the watch service if any events we registered for have occurred.

Watch service offers us no callback methods which are called whenever an event occurs. We can only poll it in a number of ways to find this information.

We can use the poll API:

WatchKey watchKey = watchService.poll();

This API call returns right away. It returns the next queued watch key any of whose events have occurred or null if no registered events have occurred.

We can also use an overloaded version that takes a timeout argument:

WatchKey watchKey = watchService.poll(long timeout, TimeUnit units);

This API call is similar to the previous one in return value. However, it blocks for timeout units of time to give more time within which an event may occur instead of returning null right away.

Finally, we can use the take API:

WatchKey watchKey = watchService.take();

This last approach simply blocks until an event occurs.

We must note something very important here: when the WatchKey instance is returned by either of the poll or take APIs, it will not capture more events if it’s reset API is not invoked:

watchKey.reset();

This means that the watch key instance is removed from the watch service queue every time it is returned by a poll operation. The reset API call puts it back in the queue to wait for more events.

The most practical application of the watcher service would require a loop within which we continuously check for changes in the watched directory and process accordingly. We can use the following idiom to implement this:

WatchKey key;
while ((key = watchService.take()) != null) {
    for (WatchEvent<?> event : key.pollEvents()) {
        //process
    }
    key.reset();
}

We create a watch key to store the return value of the poll operation. The while loop will block until the conditional statement returns with either a watch key or null.

When we get a watch key, then the while loop executes the code inside it. We use the WatchKey.pollEvents API to return a list of events that have occurred. We then use a for each loop to process them one by one.

After all the events are processed, we must call the reset API to enqueue the watch key again.

4. Directory Watching Example

Since we have covered the WatchService API in the previous subsection and how it works internally and also how we can use it, we can now go ahead and look at a complete and practical example.

For portability reasons, we are going to watch for activity in the user home directory, which should be available on all modern operating systems.

The code contains only a few lines of code so we will just keep it in the main method:

public class DirectoryWatcherExample {

    public static void main(String[] args) {
        WatchService watchService
          = FileSystems.getDefault().newWatchService();

        Path path = Paths.get(System.getProperty("user.home"));

        path.register(
          watchService, 
            StandardWatchEventKinds.ENTRY_CREATE, 
              StandardWatchEventKinds.ENTRY_DELETE, 
                StandardWatchEventKinds.ENTRY_MODIFY);

        WatchKey key;
        while ((key = watchService.take()) != null) {
            for (WatchEvent<?> event : key.pollEvents()) {
                System.out.println(
                  "Event kind:" + event.kind() 
                    + ". File affected: " + event.context() + ".");
            }
            key.reset();
        }
    }
}

And that is all we really have to do. Now you can run the class to start watching a directory.

When you navigate to the user home directory and perform any file manipulation activity like creating a file or directory, changing contents of a file or even deleting a file, it will all be logged at the console.

For instance, assuming you go to user home, right click in space, select `new – > file` to create a new file and then name it testFile. Then you add some content and save. The output at the console will look like this:

Event kind:ENTRY_CREATE. File affected: New Text Document.txt.
Event kind:ENTRY_DELETE. File affected: New Text Document.txt.
Event kind:ENTRY_CREATE. File affected: testFile.txt.
Event kind:ENTRY_MODIFY. File affected: testFile.txt.
Event kind:ENTRY_MODIFY. File affected: testFile.txt.

Feel free to edit the path to point to any directory you want to watch.

5. Conclusion

In this article, we have explored some of the less commonly used features available in the Java 7 NIO.2 – filesystem APIs, particularly the WatchService interface.

We have also managed to go through the steps of building a directory watching application to demonstrate the functionality.

And, as always, the full source code for the examples used in this article is available in the Github project.

Course – LS – All

Get started with Spring and Spring Boot, through the Learn Spring course:

>> CHECK OUT THE COURSE
res – REST with Spring (eBook) (everywhere)
Comments are open for 30 days after publishing a post. For any issues past this date, use the Contact form on the site.