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)?
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:
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.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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With