ignore file modify using Jnotify
I am using Jnotify to write an app. (JNotify is a library for for detecting file modification.)
The app has the following components:
A file writer that writes to file X
A file watcher (created using JNotify) that watches file X
An external app (such as notepad) that writes to file X as demanded by user.
I want JNotify to trigger notifications onl开发者_运维百科y when X is modified using 3, and to ignore when modified via 1. (or at least differentiate between modifications via 1 and 3).
Is there a simple way in which I can do it? One way is to have a synchronized variable that is toggled when the file writer writes to it, but I feel this is not very elegant.
In any case you need some communication between 1 + 2 to temporary disable 2 (as for 3 you have no way to do so). If 1 + 2 running in the same JVM of course the more appropiated way is to share some state in a common variable.
You may think of other smart ways to communicate. One cames to my mind: Before 1 starts to write it will generate a lock file that 2 is also lsten on. When the lock file get removed from 1 after writes are done, 2 may continue listen on the file after notified abut lock file deletion.
I tried two different ways (described below, along with the option I selected)
Option 1: use a shared boolean variable (i.e., a lock) that is toggled to true by 1. When this variable is true, 3 does not write, but instead sets it to false).
Option 2: use a shared SHA1 hash of the file. The writer (1) updates the hash every time it writes the file. The watcher (2) then checks the hash of the file modified and ignores if the hash matches the shared hash.
I decided to use Option 2 as it worked perfectly. Using Option 1, is tricky, as for every modified file, JNotify triggers two updates (strange).
精彩评论