0

I am using Jnotify to write an app. (JNotify is a library for for detecting file modification.)

The app has the following components:

  1. A file writer that writes to file X

  2. A file watcher (created using JNotify) that watches file X

  3. An external app (such as notepad) that writes to file X as demanded by user.

I want JNotify to trigger notifications only 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.

Jus12
  • 17,824
  • 28
  • 99
  • 157

2 Answers2

1

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.

PeterMmm
  • 24,152
  • 13
  • 73
  • 111
  • the lock file seems to be a good idea. However, when 1 creates the lock file, writes and removes the lock file, sometimes 2 does not have enough time. So right now I'm using `Thread.sleep(1000)` before deleting the lock file.. Not very elegant though. – Jus12 Mar 21 '11 at 17:26
  • While you cannot control 3 when write on file, you should lock the file when 1 is running. If you cannot lock the file and cannot control 3 further, there will be always the possibilty of a race condition between 1 + 3. – PeterMmm Mar 21 '11 at 20:02
0

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).

Jus12
  • 17,824
  • 28
  • 99
  • 157