DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Join us tomorrow at 1 PM EST: "3-Step Approach to Comprehensive Runtime Application Security"
Save your seat
  1. DZone
  2. Coding
  3. Java
  4. Using Google Guava EventBus with Java 7's WatchService

Using Google Guava EventBus with Java 7's WatchService

Bill Bejeck user avatar by
Bill Bejeck
·
Feb. 28, 12 · Interview
Like (0)
Save
Tweet
Share
10.19K Views

Join the DZone community and get the full member experience.

Join For Free

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/

Google Guava Event Java (programming language) Google (verb)

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • Real-Time Stream Processing With Hazelcast and StreamNative
  • The Role of Data Governance in Data Strategy: Part II
  • Mr. Over, the Engineer [Comic]
  • Last Chance To Take the DZone 2023 DevOps Survey and Win $250! [Closes on 1/25 at 8 AM]

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: