Over a million developers have joined DZone.

Using Google Guava EventBus with Java 7's WatchService

DZone's Guide to

Using Google Guava EventBus with Java 7's WatchService

· Java Zone ·
Free Resource

Download Microservices for Java Developers: A hands-on introduction to frameworks and containers. Brought to you in partnership with Red Hat.

This post is going to cover using the Guava EventBus to publish changes detected by the Java 7 WatchService. The Guava EventBus is a great way to share information while facilitating a loosely coupled architecture. The WatchService, new in the Java 7 java.nio.file package, is used to monitor a directory for changes. Since there are previous posts covering the details of the EventBus and WatchService classs, we will not be covering those topics in any depth here. For more information, the reader is encouraged to view the EventBus and WatchService posts.

Why Use the EventBus

There are two reasons for using the EventBus with a WatchService.

  1. We don’t want to poll for changes, but would rather be notified asynchronously.
  2. Once events are processed, the WatchKey.reset method needs to be called. While the WatchKey is thread safe, if there are multiple threads retrieving WatchKeys, it’s important that reset is not called until after all the events have been processed. Processing the events, calling the reset method then publishing them via the EventBus in a single thread eliminates this problem.

Registering Directories with the WatchService

The first step is to register a directory (and all it’s sub-directories) with a WatchService object:

private void registerDirectories() throws IOException {
        Files.walkFileTree(startPath, new WatchServiceRegisteringVisitor());

private class WatchServiceRegisteringVisitor extends SimpleFileVisitor<Path>{
    public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
         return FileVisitResult.CONTINUE;

On line 2 the Files.walkFileTree method uses the WatchServiceRegisteringVisitor class defined on line 5 to register every directory with the WatchService. The registered events are creation of files/directories, deletion of files/directories or updates to a file.

Publishing Events

The next step is to listen for events to publish:

 while (keepWatching) {
    WatchKey watchKey = watchService.poll(10, TimeUnit.SECONDS);
    if (watchKey != null) {
        List<WatchEvent<?>> events = watchKey.pollEvents();
        Path watched = (Path) watchKey.watchable();
        PathEvents pathEvents = new PathEvents(watchKey.isValid(), watched);
        for (WatchEvent event : events) {
            pathEvents.add(new PathEvent((Path) event.context(), event.kind()));

On line 2, we are checking the WatchService every 10 seconds for queued events. When a valid WatchKey is returned, the first step is to retrieve the events (line 4) then get the directory where the events occurred (line 5). On line 6 a PathEvents object is created, taking a boolean and the watched directory as constructor arguments. Lines 7-10 are looping over the events retrieved on line 4, using the target Path and event type as arguments to create PathEvent object. The WatchKey.reset method is called on line 11, setting the WatchKey state back to ready, making it eligible to receive new events and be placed back into the queue. Finally on line 12 the EventBus publishes the PathEvents object to all subscribers. It’s important to note here that the PathEvents and PathEvent classes are immutable.


By pairing the WatchService with the Guava EventBus we are able to manage the WatchKey and process events in a single thread and notify any number of subscribers asynchronously of the events. It is hoped the reader found this example useful. As always comments and suggestions are welcomed.


From http://codingjunkie.net/eventbus-watchservice/

Download Building Reactive Microservices in Java: Asynchronous and Event-Based Application Design. Brought to you in partnership with Red Hat


Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}