Sotirios Delimanolis Sotirios Delimanolis - 11 months ago 126
Java Question

Java 7 WatchService - Ignoring multiple occurrences of the same event

The javadoc for


Directory entry modified. When a directory is registered for this
event then the WatchKey is queued when it is observed that an entry in
the directory has been modified. The event count for this event is 1
or greater.

When you edit the content of a file through an editor, it'll modify both date (or other metadata) and content. You therefore get two
events, but each will have a
of 1 (at least that's what I'm seeing).

I'm trying to monitor a configuration file (
previously registered with the
) that is manually updated (ie. through command line
) with the following code:

while(true) {
watchKey = watchService.take(); // blocks

for (WatchEvent<?> event : watchKey.pollEvents()) {
WatchEvent<Path> watchEvent = (WatchEvent<Path>) event;
WatchEvent.Kind<Path> kind = watchEvent.kind();

System.out.println(watchEvent.context() + ", count: "+ watchEvent.count() + ", event: "+ watchEvent.kind());
// prints (loop on the while twice)
// servers.cfg, count: 1, event: ENTRY_MODIFY
// servers.cfg, count: 1, event: ENTRY_MODIFY

switch( {
handleModify(watchEvent.context()); // reload configuration class
handleDelete(watchEvent.context()); // do something else


Since you get two
events, the above would reload the configuration twice when only once is needed. Is there any way to ignore all but one of these, assuming there could be more than one such event?

If the
API has such a utility so much the better. (I kind of don't want to check times between each event. All the handler methods in my code are synchronous.

The same thing occurs if you create (copy/paste) a file from one directory to the watched directory. How can you combine both of those into one event?

Answer Source

I had a similar issue - I am using the WatchService API to keep directories in sync, but observed that in many cases, updates were being performed twice. I seem to have resolved the issue by checking the timestamp on the files - this seems to screen out the second copy operation. (At least in windows 7 - I can't be sure if it will work correctly in other operation systems)

Maybe you could use something similar? Store the timestamp from the file and reload only when the timestamp is updated?