Search code examples
javacentoscpu-usagewatchservice

WatchService uses 100% of CPU on CentOS


I am using a WatchService in my application. When I run my application on a Windows environment, the application uses less than 1% of the CPU. When the same application is run on my Linux server, it uses 100% of the CPU. When the WatchService thread is disabled, the CPU is back to normal.

I am using CentOS 5.9 with OpenJDK-1.7.0_x86_64.

Here is the thread:

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();
    }
}

Why is it using 100% of the CPU?


Solution

  • I had the same issue on Ubuntu 16.04.

    sudo apt-get install inotify-tools dropped my resource usage considerably. Not sure what/if inotify-hookable also helps, but it comes with a lot more dependencies, so maybe hold off on that unless inotify-tools is not enough.

    Thx to comment by @Thomas Jungblut for this solution.