gpt4 book ai didi

java - 如何正确处理 watchservice 中的 pollEvents() 溢出类型?

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:34:26 25 4
gpt4 key购买 nike

我正在使用监视服务来监视目录并在新创建的文件上触发逻辑。我最近遇到的挑战之一是当大量文件需要处理并且被快速复制到监视目录而无法处理时会触发溢出。

API说到溢出:

File systems may report events faster than they can be retrieved or processed and an implementation may impose an unspecified limit on the number of events that it may accumulate. Where an implementation knowingly discards events then it arranges for the key's pollEvents method to return an element with an event type of OVERFLOW.

我的问题是,如何正确处理溢出,而不丢失任何需要处理的事件?

我的 watchservice 代码如下:

            Path myDir = Paths.get(srcDir);
try(WatchService watcher = myDir.getFileSystem().newWatchService()){
myDir.register(watcher, ENTRY_CREATE,ENTRY_MODIFY);
int x = 0;
for(;;){
x++;
WatchKey watchKey = watcher.take();
LOGGER.debug("Event # {}",x);
List<WatchEvent<?>> events = watchKey.pollEvents();
LOGGER.info("Events Size {}",events.size());
for (WatchEvent event : events) {
if(event.kind() == OVERFLOW){
LOGGER.error("The Maximum watchService events has been reached!");
System.exit(1); //I exit so I know there is a problem - but how should I handle this?
}
if (event.kind() == ENTRY_CREATE) {
LOGGER.info("File created: " + event.context().toString());
LOGGER.info("Beginning Processing:" +event.context().toString());
...business logic here...
}
}
watchKey.reset();
}
...

最佳答案

我在实践中从未见过溢出事件。它的意思是通知您您将需要重新处理您正在观看的任何目录。您无需退出程序,只需使用单线程 File.list() 调用来抓取目录。我在下面剪切粘贴了我的处理方式。这段代码...

1) 记录一个问题

2) 设置一个标志来触发目录重新处理,爬取目录中的所有文件

3) 跳过此 WatchEvent 的其余处理

// log overflow events and trigger reprocess later.
if (kind == OVERFLOW)
{
logger.warn("File listener recieved an overflow event. You should probably check into this");
overflowTriggeredFlag = true;
continue;
}

关于java - 如何正确处理 watchservice 中的 pollEvents() 溢出类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17927486/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com