Event fired only once when watching a directory

So I had to keep an eye on one of the directory and whenever one of the files got modified, I had to do something. For this I wrote a simple code using Java’s WatchService. Things worked fine for the first event but somehow events were not getting fired if file was modified multiple times. For first modification, I got the event. This was a strange behavior

 
 final WatchService watcher = FileSystems.getDefault().newWatchService();
            Path dir = Paths.get(ServiceFactory.getRuntimeService().getWebRoot() + "\\CFIDE\\cache\\");
            dir.register(watcher, StandardWatchEventKinds.ENTRY_MODIFY);
 
 new Thread()
            {
 
                @Override
                public void run()
                {
                    while (true)
                    {
                        WatchKey key = null;
                        try
                        {
                            key = watcher.take();
                        }
                        catch (InterruptedException e)
                        {
 
                        }
                        List<WatchEvent<?>> events = key.pollEvents();
                        for (WatchEvent<?> event : events)
                        {
                            Path p = ((WatchEvent<Path>) event).context();
                            Kind<?> kind = event.kind();
                            if (p.endsWith(cacheName + ".cfc") && kind == StandardWatchEventKinds.ENTRY_MODIFY)
                            {
                                proxy = null;
                            }
                        }
 
 
 
                    }
                }
            }.start();

So after some googling I found that we need to reset the ‘key’ once while loop is done. If that is not done, it is as good as watcherservice is disabled and that is why we do not get further events. So this code is required at the end of loop :

key.reset();

After the events for the key have been processed, you need to put the key back into a ready state by invoking reset. If this method returns false, the key is no longer valid and the loop can exit. This step is very important. If you fail to invoke reset, this key will not receive any further events.

Uday Ogra

Connect with me at http://facebook.com/tendulkarogra and lets have some healthy discussion :)

You may also like...

Leave a Reply

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