WatchService在CentOS上使用100%的CPU

时间:2014-07-14 14:47:12

标签: java centos cpu-usage watchservice

我在我的应用程序中使用了WatchService。当我在Windows环境中运行我的应用程序时,应用程序使用的CPU不到1%。在我的Linux服务器上运行相同的应用程序时,它会使用CPU的100%。禁用WatchService主题后,CPU恢复正常。

我将CentOS 5.9OpenJDK-1.7.0_x86_64一起使用。

以下是主题:

private static void startDirectoryWatcher() {
    if (thWatcherM == null) {
        thWatcherM = new Thread(new Runnable() {
            @Override
            public void run() {
                if (mediaMode == MediaMode.Directory && !exit) {

                    File music = new File(path);

                    WatchService watcherM = null;

                    watcherM = music.toPath().getFileSystem().newWatchService();
                    music.toPath().register(watcherM, StandardWatchEventKinds.ENTRY_CREATE);

                    while (!exit) {
                        Thread.sleep(50);
                        if (watcherM != null) {
                            WatchKey watchKey = watcherM.take();

                            List<WatchEvent<?>> events = watchKey
                                    .pollEvents();
                            for (WatchEvent<?> event : events) {
                                if (event.kind() == StandardWatchEventKinds.ENTRY_CREATE) {
                                    System.out.println(event.context().toString());
                                }
                            }

                            if (!watchKey.reset()) {
                                break;
                            }
                        }
                    }

                    if (watcherM != null) {
                        watcherM.close();
                    }

                }
            }
        });
        thWatcherM.setName("Dir-Watcher-M");
        thWatcherM.start();
    }
}

为什么使用CPU 100%

1 个答案:

答案 0 :(得分:1)

我在Ubuntu 16.04上遇到了同样的问题。

sudo apt-get install inotify-tools大大减少了我的资源使用量。不知道是什么/如果inotify-hookable也有帮助,但它带来了更多的依赖关系,所以可能暂缓,除非inotify-tools是不够的。

由@Thomas Jungblut评论此解决方案。