documentation for the overflow状态:
OVERFLOW – Indicates that events might have been lost or discarded.
它没有说明在什么情况下我应该期望事件丢失或丢弃?起初我以为这是将大量文件非常快速地写入文件夹的结果。我创建了几千个零大小的文件,并将它们移动到受监控的目录中。没有溢出。
我错过了什么?
最佳答案
产生溢出的最小示例
只需在 watcherService.register
之后和 watcherService.take
之前创建文件即可。
调用方式:
java Overflow 256
控制事件的数量。
Java 7 和 Ubuntu 14.04 最多可处理 512 个事件。
每次发生溢出时,pollEvents()
只返回一个事件,但这在 Javadoc 中并没有明确说明。
我觉得这个限制这么小很奇怪,考虑到:
- 我的
sysctl fs.inotify.max_user_watches
是524288
- https://unix.stackexchange.com/questions/13751/kernel-inotify-watch-limit-reached
- JDK 似乎在 Linux 上使用
inotify
:http://hg.openjdk.java.net/jdk7u/jdk7u60/jdk/file/33c1eee28403/src/solaris/native/sun/nio/fs/LinuxWatchService.c#l36
代码:
import java.io.File;
import java.io.IOException;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardWatchEventKinds;
import java.nio.file.WatchEvent;
import java.nio.file.WatchService;
import java.util.List;
public class Overflow {
@SuppressWarnings("unchecked")
static <T> WatchEvent<T> cast(WatchEvent<?> event) {
return (WatchEvent<T>)event;
}
public static void main(final String[] args) throws InterruptedException, IOException {
int nfiles;
if (args.length > 0)
nfiles = Integer.parseInt(args[0]);
else
nfiles = 10_000;
Path directory = Files.createTempDirectory("watch-service-overflow");
final WatchService watchService = FileSystems.getDefault().newWatchService();
directory.register(
watchService,
StandardWatchEventKinds.ENTRY_CREATE,
StandardWatchEventKinds.ENTRY_DELETE);
final Path p = directory.resolve(Paths.get("Hello World!"));
for (int i = 0; i < nfiles; i++) {
Files.createFile(p);
Files.delete(p);
}
List<WatchEvent<?>> events = watchService.take().pollEvents();
for (final WatchEvent<?> event : events) {
if (event.kind() == StandardWatchEventKinds.OVERFLOW) {
System.out.println("Overflow.");
System.out.println("Number of events: " + events.size());
return;
}
}
System.out.println("No overflow.");
Files.delete(directory);
}
}
关于java - jdk7 watch service API中,什么时候会抛出OVERFLOW事件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18586091/