Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WatchService (Windows 7): when deleting a file, it fires both ENTRY_MODIFY and ENTRY_DELETE events?

In working with the WatchService, I found that if I delete a file in the directory being watched, it fires an ENTRY_MODIFY followed by an ENTRY_DELETE event.

I realize that technically, a file may be modified before deleted, but is it really the expected behavior that deleting a file will trigger ENTRY_MODIFY (which presumably no one cares about)?

To handle this, I had to add a condition to check before firing passing along the ENTRY_MODIFY event:

            if (eventKind == ENTRY_CREATE) {
                listener.fileCreated(file);
            } else if (eventKind == ENTRY_MODIFY) {
                if (Files.exists(fullPath, LinkOption.NOFOLLOW_LINKS)) {
                    listener.fileChanged(file);
                }
            } else if (eventKind == ENTRY_DELETE) {
                listener.fileDeleted(file);
            }

Is this there a better way to handle this issue (feature)?

like image 909
Sam Goldberg Avatar asked Oct 31 '22 10:10

Sam Goldberg


1 Answers

I can only confirm the issue. From the comments and from my own observations, the ENTRY_MODIFY event is fired just before the file is deleted and you have to deal with it.

Suppose we have two threads. One is doing Files.delete(), the other is watching the directory and trying to read modified files. Any of the following can happen:

  1. Files.delete() just manages to modify and delete the file, before the event is picked up by the watching thread. Then the technique to check the file existence after ENTRY_MODIFY works.
  2. the Files.delete() call can fail (return false), as the file is already opened by the watching thread.

The only resolution seems to be to ignore all IOExceptions in the watching thread and to retry the Files.delete() call few times.

I only tried to delete the files from the same JVM with Files.delete(). I did not try to delete from other process on the system. Problem reproduces on Windows 7~10 with NTFS, probably not on other OSes.

I encourage others to edit this answer and add their observations.

like image 142
Oliv Avatar answered Nov 15 '22 05:11

Oliv