Bill Bejeck is a software developer and enjoys the challenges that software development brings. Bill also loves exploring new languages, technologies and learning and educating by blogging. Bill is a DZone MVB and is not an employee of DZone and has posted 29 posts at DZone. You can read more from them at their website. View Full User Profile

Using Google Guava EventBus with Java 7's WatchService

02.28.2012
| 6259 views |
  • submit to reddit

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>{
    @Override
    public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
         dir.register(watchService,ENTRY_CREATE,ENTRY_DELETE,ENTRY_MODIFY);
         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()));
            totalEventCount++;
        }
        watchKey.reset();
        eventBus.post(pathEvents);
    }
}

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.

Conclusion

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/

Published at DZone with permission of Bill Bejeck, author and DZone MVB.

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)

Tags: