4

WatchService在我的应用程序中使用 a 。当我在环境中运行我的应用程序时Windows,该应用程序使用不到 1% 的CPU. 当相同的应用程序在我的Linux服务器上运行时,它使用 100% 的CPU. 当WatchService线程被禁用时,CPU它恢复正常。

我正在CentOS 5.9使用OpenJDK-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();
    }
}

为什么它使用100%CPU?

4

1 回答 1

1

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

sudo apt-get install inotify-tools 大大降低了我的资源使用量。不确定什么/如果 inotify-hookable 也有帮助,但它带有更多的依赖项,所以除非 inotify-tools 还不够,否则可能会推迟。

感谢@Thomas Jungblut 对此解决方案的评论。

于 2017-01-27T17:19:35.290 回答