Java WatchService Duplicate Event Fix

In a previous post, I provided the Java WatchService Sample Code that works fine. However, if you run the code you will notice a behavior that is exhibited by the Java WatchService that you may not expect. The problem is that when you edit a file, the WatchService Interface will register what looks like duplicate events for a single change. In reality, the Interface is designed to register a)an event for the new/changed file and b)an event for the new modification time of the file that changed.

There are a couple of fixes for this, but the easiest fix is to place a short sleep() just before calling pollEvents(). I included the original code below with the addition of the Thread.sleep() call. I am setting the sleep() method to 2 seconds (2000 ms).


Java WatchService Duplicate Event Fix

package com.jcd.java.tutorials;


import java.nio.file.WatchEvent;
import java.nio.file.WatchEvent.Kind;
import java.nio.file.WatchKey;
import java.nio.file.WatchService;


public class JavaWatchServiceRunnable implements Runnable
{

	WatchService watchService;
	
	public JavaWatchServiceRunnable (WatchService myWatchService) 
	{
		watchService = myWatchService;
	}
	
	@Override
	public void run() 
	{
		try 
		{         
			
			System.out.println("\nMy Runnable Waiting on Events!\n");
			
			WatchKey key = watchService.take();
			
			while(key != null) {
				
				//////////////////////////////////////////////////////
				//Sleep for 2 seconds to elminate the duplicate event
				//////////////////////////////////////////////////////
				Thread.sleep( 2000 );

                for (WatchEvent watchEvent : key.pollEvents())
                {   	
                	Kind<?> kind = watchEvent.kind();
                	
                	System.out.println("New Event: "+watchEvent.context() + " --> " + kind.toString());
                }
                
                //Make sure to reset the event that just happened
                key.reset();
                key = watchService.take();
			}
			
		} catch (Exception ex) 
		{
			System.out.println("Exception:"+ex.toString());
		}
	}
		
}



Java References:

Add a Comment

Your email address will not be published. Required fields are marked *