我在我的应用程序中使用了 WatchService
。当我在 Windows
环境中运行我的应用程序时,该应用程序使用的 CPU
不到 1%。当同一个应用程序在我的 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
?
最佳答案
我在 Ubuntu 16.04 上遇到了同样的问题。
sudo apt-get install inotify-tools 大大降低了我的资源使用率。不确定什么/如果 inotify-hookable 也有帮助,但它有更多的依赖关系,所以除非 inotify-tools 不够,否则可能会推迟。
感谢@Thomas Jungblut 对此解决方案的评论。
关于java - WatchService 在 CentOS 上使用 100% 的 CPU,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24739280/