WatchService uses 100% CPU on CentOS

I use WatchServicein my application. When I run the application in the environment Windows, the application uses less than 1% of CPU. When the same application runs on my server Linux, it uses 100% of CPU. When the stream is WatchServiceturned off, it CPUreturns to normal.

I use CentOS 5.9with 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 he using 100% for CPU?

+4
source share
1 answer

I had the same issue on Ubuntu 16.04.

sudo apt-get install inotify-tools . , /if inotify-hookable , , , , , inotify .

, @Thomas Jungblut .

+1

Source: https://habr.com/ru/post/1548359/


All Articles