我在我的应用程序中使用了WatchService
。当我在Windows
环境中运行我的应用程序时,应用程序使用的CPU
不到1%。在我的Linux
服务器上运行相同的应用程序时,它会使用CPU
的100%。禁用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();
}
}
为什么使用CPU
的 100%?
答案 0 :(得分:1)
我在Ubuntu 16.04上遇到了同样的问题。
sudo apt-get install inotify-tools大大减少了我的资源使用量。不知道是什么/如果inotify-hookable也有帮助,但它带来了更多的依赖关系,所以可能暂缓,除非inotify-tools是不够的。
由@Thomas Jungblut评论此解决方案。