Our products currently using JDK 1.6, so we have to rely on JNotify for file system changes. However during the test I noticed something that worked perfect in my Win 7 development environment stop working in XP and win server 2003. So I move on to wrote a small test program. Here is what it roughly looks like.
In the main class I only have this:
public static void main(String[] args) {
SyncUtil instance = new SyncUtil();
instance.start();
Scanner s = new Scanner(System.in);
s.nextLine();
}
SyncUtil is a class that extends Threads:
public void run() {
String path = "D:\\testFolder";
int mask = JNotify.FILE_CREATED | JNotify.FILE_DELETED | JNotify.FILE_MODIFIED | JNotify.FILE_RENAMED;
boolean watchSubtree = true;
File file = null;
try {
JNotify.addWatch(path, mask, watchSubtree, new Listener());
} catch (Exception e) {
e.printStackTrace();
}
}
The Listener class don't have any work inside, It just print log. Now, If I run the above sample on Windows 7 / 8. It will work just fine. But when I test it on my Win Server 2003, JNotify just stop working and Listener will not print any log at all.
What's more interesting though is if I try to make SyncUtil wait a minute when after its work. If I add:
Thread.sleep(60000);
to the end of the run function to make it wait for 60 seconds. And instead of monitoring 1 folder, this time I'll monitor 2, I'll call them folder A and B.
What happens on the Win Server 2003 machine in this case is that if I add a file to folder A within the 60s waiting time, JNotify will properly react to the event and print a log. And it will even keep on working even if 60s has passed and the SyncUtil Thread is terminated. But now I add a file to folder B (after the 60s waiting time that is), nothing will be printed.
To sum it up, the symptom is: 1. On win 7 and win 8, JNotify will keep on working disregard of whether or not the thread calls for JNotify.addWatch() is still alive. 2. On win XP and win server 2003, JNotify can properly generate event when The Thread calls JNotify.addWatch() is running. Paths that generated at least one event when that Thread is still alive will continue to be monitored after that thread is terminated. But those paths that didn't generate any event when said thread is alive, will not work after that thread is terminated.
Now knowing this pattern I'm currently using a CountDownLatch to fix the issue, but I'm just really curious why this is happening. I feel this kind of don't make any sense, where do you think the problem is? I'm leaning towards the conclusion that maybe windows trigger file system event differently? Do you think this might be the case?