Using OperatingSystemMXBean to get CPU usage

橙三吉。 提交于 2019-11-29 06:22:08

Just answering my own question in case it could help somebody.

What I was doing was technically correct, however I was not giving the OperatingSystemMXBean enough time to gather CPU usage information. The JVM must actually be running for a few seconds before it can gather CPU usage information, and then the refresh resolution is implementation-dependent it would seem.

Running the code with the following change will start to produce usage information after ~2 seconds on my machine:

public static void main(String[] args) {
    OperatingSystemMXBean bean = (com.sun.management.OperatingSystemMXBean) ManagementFactory
            .getOperatingSystemMXBean();

    while (true) {
        System.out.println(bean.getProcessCpuLoad());
        System.out.println(bean.getSystemCpuLoad());
    }

}

Hopefully this can help somebody

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!