public void run() {
for (;;) {
// take() will block until a file has been created/deleted
WatchKey signalledKey;
try {
signalledKey = watchService.take();
} catch (InterruptedException ix) {
// we'll ignore being interrupted
if (log != null) {
log.append("Interrupted\n");
}
continue;
} catch (ClosedWatchServiceException cwse) {
// other thread closed watch service
System.out.println("watch service closed, terminating.");
break;
}
List<WatchEvent<?>> list;
Path watchedPath;
EventsStackerRunnable stacker;
synchronized (lock) {
synchronized (keyToPathLock) {
watchedPath = keyToPath.get(signalledKey);
}
if (watchedPath == null) {
continue;
}
// get list of events from key
list = signalledKey.pollEvents();
stacker = pathToStacker.get(watchedPath);
if (stacker == null) {
//if the stacker does not exist, go on without rescheduling the key!
if (log != null) {
log.append("Stacker for: ").appendObject(watchedPath).append("is null\n");
}
continue;
}
runnables.add(stacker);
for (WatchEvent<?> e : list) {
Path context = (Path) e.context();
Path resolve = watchedPath.resolve(context);
File file = new File(resolve.toString());
Kind<?> kind = e.kind();
if (log != null) {
log.append("Event: ").appendObject(e).append('\n');
}
if (kind == StandardWatchEventKind.OVERFLOW) {
if (!file.exists()) {
//It may be that it became invalid...
synchronized (keyToPathLock) {
keyToPath.remove(signalledKey);
}
stacker.key = null;
addInvalidPath(stacker);
stacker.removed(file);
} else {
// VERY IMPORTANT! call reset() AFTER pollEvents() to allow the
// key to be reported again by the watch service.
signalledKey.reset();
if (log != null) {
log.append("Key reset to hear changes");
}
}
//On an overflow, wait a bit and signal that all files being watched were removed,
//do a list and say that the current files were added again.
stacker.overflow(file);
} else {
if (kind == StandardWatchEventKind.ENTRY_CREATE
|| kind == StandardWatchEventKind.ENTRY_MODIFY) {
// VERY IMPORTANT! call reset() AFTER pollEvents() to allow the
// key to be reported again by the watch service.
signalledKey.reset();
if (log != null) {
log.append("Key reset to hear changes");
}
stacker.added(file);
} else if (kind == StandardWatchEventKind.ENTRY_DELETE) {
// VERY IMPORTANT! call reset() AFTER pollEvents() to allow the
// key to be reported again by the watch service.
signalledKey.reset();
if (log != null) {
log.append("Key reset to hear changes");
}
stacker.removed(file);