java - jdk7 watch service API中,什么时候会抛出OVERFLOW事件?

标签 java io java-7 nio2

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 中并没有明确说明。

我觉得这个限制这么小很奇怪,考虑到:

代码:

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/

相关文章:

java - 如何在 java 中配置 war 应用程序以允许从 GET 方法访问资源目录?

java - 谁能帮我创建方法? mystring.replacefirst(字符串,字符串);并替换(自,直到,字符串);对于j2me,请

python - python高效读取数据(仅一行)

database - Oracle 查询检查数据库中所有事件查询的 I/O 消耗

java - Spark 和 Cassandra Java 应用程序 : Exception in thread "main" java. lang.NoClassDefFoundError: org/apache/spark/sql/Dataset

java - 测试我的 Java UDP 对等程序时出现问题

java - Netty 乒乓球与 POJO

java - Intellij 中的使用 API 错误

java - 为什么不能在 try-with-resources try 子句中重用引用变量?

java - 锁可以自动关闭吗?