我有一个应用程序,当将文件添加到目录时,WatchService 会检测到该文件并将该文件添加到文件列表中以进行进一步处理。这是我的代码
public void run() {
/*
* Goes in an infinite loop
*/
while(!finished) {
/*
* Get a watch key, poll() returns a queued key
* if no queued key, this method waits until the specified time.
*/
WatchKey key;
try {
key = watcher.poll(eofDelay,TimeUnit.MILLISECONDS);
} catch (InterruptedException x) {
return;
}
Path dir = keys.get(key);
if (dir == null) {
continue;
}
Path child=null;
/*
* Fetching the list of watch events from
* pollEvents(). There are four possible events
*/
for (WatchEvent<?> event: key.pollEvents()) {
WatchEvent.Kind kind = event.kind();
/*
* Overflow indicates that events
* might have been lost or discarded
*/
if (kind == OVERFLOW) {
continue;
}
WatchEvent<Path> ev = cast(event);
/*
* Filename is the context of the event
*/
Path name = ev.context();
/*
* Resolves the name of the file to a path
*/
child = dir.resolve(name);
/*
* If directory is created, and watching recursively, then
* register it and its sub-directories
*/
if (nested && (kind == ENTRY_CREATE)) {
try {
if (Files.isDirectory(child, NOFOLLOW_LINKS)) {
registerAll(child);
}
} catch (IOException x) {
}
}
}
File file = child.toFile();
/*
* Only add the file if there is no wild card
* or it matches the specified wild card
*/
if (matcher == null || matcher.matches(file.toPath().getFileName())) {
fileList.add(file);
}
/*
* Key is reset so that it can receive further
* events
*/
boolean valid = key.reset();
if (!valid) {
keys.remove(key);
/*
* If key is no longer valid and empty,
* exit the loop
*/
if (keys.isEmpty()) {
continue;
}
}
}
}
此代码按预期工作,但我正在设计一个高性能应用程序,它以非常高的速度处理文件中的数据。所以这里的问题是检测文件所用的时间不一致。例如,最初目录中有一些文件,它们由应用程序处理,现在当添加新文件时,检测文件需要 4-5 秒,有时需要 2 秒或 20 毫秒等。我的 eofDelay 值为 10 毫秒。这种不一致的原因是什么?有没有办法增强这个实现?或者任何其他可用于目录更改的高效库?我希望检测文件所花费的时间最少且一致,花费一秒钟以上的时间非常昂贵。在这方面的任何帮助将不胜感激。:)