Search code examples
javawatchservice

WatchService getting fired multiple times (MODIFY is fired and even before CREATE is finished) JAVA


I have a Service which checks for a ZIP file in a folder,

while(true) {
       WatchKey wk = watchService.take();
       for (WatchEvent<?> event : wk.pollEvents()) {

            Kind<?> eventKind = event.kind();

            Path dir = (Path)wk.watchable();
            Path eventPath = (Path) event.context();

            Path fullPath = dir.resolve(eventPath);
            fireAction(eventKind, fullPath);   
        }

        wk.reset();
 }

Here if you see, everytime an action is performed fireAction() method is called, below is the method

public void fireAction(Kind<?> eventKind, Path eventPath) {
        
        synchronized (listeners) {

            if (eventKind == StandardWatchEventKinds.ENTRY_MODIFY) {
                
                fileModified(this, eventPath);
                
            } else if (eventKind == StandardWatchEventKinds.ENTRY_DELETE) {

                fileDeleted(this, eventPath);
                
            } else if (eventKind == StandardWatchEventKinds.ENTRY_CREATE) {

                fileCreated(this, eventPath);
            }
        }
    }

So when the folder is empty and I keep my ZIP in the folder for first time, fileCreate() method is called but it dont finish and fileModify() method gets triggered, and fileModify() gets triggered 2 times. When I delete the ZIP from the folder, it works okay, but when I keep my ZIP again, it is working okay.

SO ONLY FIRST TIME THE PROBLEM OCCURS. PLEASE ANY SUGGESTION, this is what I have tried

  1. Thread.sleep(3000) between take() and pollEvents(), outside for loop.
  2. Using .lastModified() to see if file was updated, however I am not sure if I did it correctly, is there any other way? Please suggest

Solution

  • generate a checksum for the file you are creating and store the checksum in value and set key as path to file in a map, and when modify is getting fired, just validate the checksum and file,

    if checksum exist, dont modify, else modify.

    Should be easy to implement, i did same.