我已经创建了一个监视文件夹的小型Java应用程序。它使用观察者模式来通知不同的fileHandlers。文件处理程序操作可能需要几秒钟的时间来处理文件。如果它一次只处理一个项目,那么所有的工作都很好。如果新文件到达,则在前一个文件完成之前,它将错过事件,并且不会检测到新文件。解决此问题的最佳模式是什么?我代码的某一部分...
WatchService watcher = FileSystems.getDefault().newWatchService();
List<Path> allPaths = new ArrayList<Path>();
Path path = Paths.get("c:\InPutFolder");
allPaths.add(path);
// Register all paths in the WatchService
Map<WatchKey, Path> allKeys = new HashMap<>();
for (Path path : allPaths) {
WatchKey key = path.register(watcher, StandardWatchEventKinds.ENTRY_CREATE);
allKeys.put(key, path);
}
// Monitor the folders and listen for change notification.
while (true) {
WatchKey key = watcher.take();
for (WatchEvent<?> event : key.pollEvents()) {
WatchEvent.Kind<?> kind = event.kind();
if (ENTRY_CREATE.equals(kind)) {
Path path = allKeys.get(key);
// Store item in arrayList of objects
Item item = new Item(path.toString(), event.context().toString());
ic.addItem(item);
notifyObservers(); // NOTIFY OBSERVERS & EXECUTE LONG PROCESS
}
}
key.reset();
}发布于 2021-01-12 10:45:29
我有一个类似的实现,有一个等待文件的服务。从这个article
当poll或take API返回WatchKey实例时,如果不调用它的reset API,它将不会捕获更多事件
因此,在take和reset调用之间,您不会收到事件。解决方案是获取事件(或事件中的数据)并调用reset。我使用一个线程池,并在一个Runnable实例中处理每个事件。如果您想深入了解线程路径,请看一看java的ExecutorService。但是,您需要确保无论长时间运行的进程调用的是什么,都是线程安全的。
没有理由不能获取所有的事件信息,然后调用reset并在调用reset之后同步处理这些事件。如果您这样做了,那么您可能应该捕获OVERFLOW事件,以便您知道何时错过了事件。
https://stackoverflow.com/questions/65675948
复制相似问题