gpt4 book ai didi

java - WatchService 在 CentOS 上使用 100% 的 CPU

转载 作者:搜寻专家 更新时间:2023-11-01 03:37:56 25 4
gpt4 key购买 nike

我在我的应用程序中使用了 WatchService。当我在 Windows 环境中运行我的应用程序时,该应用程序使用的 CPU 不到 1%。当同一个应用程序在我的 Linux 服务器上运行时,它使用了 100% 的 CPU。当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();
}
}

为什么它使用 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com