尝试对目录进行watchservice时发生异常中断

时间:2019-07-13 06:12:49

标签: java watchservice interrupted-exception

我正在尝试编写监视服务来监视对多个目录的更改。我写了一个测试来验证它的工作。因此,我有一个临时文件夹,在该文件夹下创建两个目录subdir1 / anotherdir1和subdir2 / anotherdir2。我为这两个目录注册了监视服务。当我将某些文件移动到subdir1 / anotherdir1时,遇到了“异常中断”。

最初,两个目录是tempfolder /和tempfolder / subdir2 / anotherdir2。我曾考虑将tempfolder /更改为tempfolder / subdir1 / anotherdir1,但仍然看到监视服务被中断。我试图修改代码以仅监视一个目录,但异常仍然存在。

我使用以下选项注册

      WatchKey key = dirPath.register(service,
              StandardWatchEventKinds.ENTRY_CREATE,
              StandardWatchEventKinds.ENTRY_MODIFY,
              StandardWatchEventKinds.ENTRY_DELETE,
              StandardWatchEventKinds.OVERFLOW);
      watchKeyPathMap.put(watchkey, dirPath);

run方法看起来像-

public void run() {
  for (Key key : map.keySet()) {
    LOG.info("listening -  {}", map.get(key));
  }
  try {
    runWatcher(watchService, map);
  } catch (InterruptedException ie) {
    LOG.warn("Watching {} was interrupted.", map, ie);
  } catch (Exception e) {
    LOG.warn("Stopping watching. ", e);
  } finally {
    close();
  }
}

runWatcher方法如下-

private void runWatcher(WatchService service, Map<WatchKey, Path> map)
        throws InterruptedException {
  boolean valid = true;
  WatchKey key = null;
  while (valid) {
    key = service.take();
    for (WatchEvent<?> event: watchKey.pollEvents()) {
      if (filename.toString().contains(fileMoved1)) {
        calltoMethod2();
      } else if (filename.toString().contains(fileMoved2)) {
          updateLogicalClusterMetadata();
      }
    }
    valid = key.reset();
  }
  LOG.warn("stopped watch service.", map.get(key));
}

堆栈跟踪如下所示-

WARN观看java.lang.InterruptedException     在java.util.concurrent.locks.AbstractQueuedSynchronizer $ ConditionObject.reportInterruptAfterWait(AbstractQueuedSynchronizer.java:2014)     在java.util.concurrent.locks.AbstractQueuedSynchronizer $ ConditionObject.await(AbstractQueuedSynchronizer.java:2048)     在java.util.concurrent.LinkedBlockingDeque.takeFirst(LinkedBlockingDeque.java:492)     在java.util.concurrent.LinkedBlockingDeque.take(LinkedBlockingDeque.java:680)     在sun.nio.fs.AbstractWatchService.take(AbstractWatchService.java:118)

线路键= service.take();在runWatcher中抛出Interrupted Exception时,堆栈跟踪似乎没有提供足够的上下文,因此我在此问题上停留了一段时间。

0 个答案:

没有答案