1

Does anyone know how to get CPU Utilization Rate in Java 17? I'm trying:

import com.sun.management.OperatingSystemMXBean;
public class Main {
    public static void main(String[] args) throws Exception {
        OperatingSystemMXBean osBean = ManagementFactory.getPlatformMXBean(
                OperatingSystemMXBean.class);

        System.out.println(osBean.getCpuLoad());
     }
}

I realized that CPU utilization should not be confused with CPU load. So I believed that my function getCpuLoad is not what I expected. So my question is: What is the function to get CPU Utilization Rate?

all ng
  • 23
  • 3
  • 1
    You imported the wrong class. Use [java.lang.management.OperatingSystemMXBean](https://docs.oracle.com/en/java/javase/17/docs/api/java.management/java/lang/management/OperatingSystemMXBean.html). Never import a class starting with “sun.” or “com.sun.”. – VGR Mar 19 '22 at 03:16
  • @VGR I tried with your import solution but the function getCpuLoad() got wrong\ – all ng Mar 19 '22 at 03:18
  • Apparently you can cast the returned MXBean to com.sun.management.OperatingSystem.MXBean, according to [the documentation](https://docs.oracle.com/en/java/javase/17/docs/api/jdk.management/com/sun/management/OperatingSystemMXBean.html). – VGR Mar 19 '22 at 03:24
  • @VGR I just realized that CPU utilization should not be confused with CPU load. So I believe that my function getCpuLoad is not what I expected. Do you have any idea to get CPU Utilization Rate? – all ng Mar 19 '22 at 03:32

0 Answers0