I'm trying to get CPU utilization or usage using Java 11.
My expectation is the average percentage of total usage, I don't really have any interest in the number of cores or thread available on the CPU.
In simple term on 80% the CPU is very busy, and on 10% is more or less idling.
How do I get this?
I've been trying a couple of suggestions from stackoverflow.
Option 1. Using com.sun.management.OperatingSystemMXBean is not good, anything com.sun is old and should be avoided.
Option 2. There is a 3rd party org.hyperic.sigar.CpuInfo which seems to be old and no longer maintained project. The result of cpuInfo.getVendor(), cpuInfo.getModel() below is null null. That gives me confidence (sacarsm).
protected void getCPUUtilization4() {
CpuInfo cpuInfo = new CpuInfo();
System.out.println(String.format(" CpuInfo: %s %s", cpuInfo.getVendor(), cpuInfo.getModel()));
}
Option 3. Built-in inside Java java.lang.management.OperatingSystemMXBean. The problem with this option is the osBean.getSystemLoadAverage() is a double value. When my cpu is not busy ~ 1.3 , and when my CPU is busy reached up to ~2.9. The osBean.getAvailableProcessors() returns 8. I'm pretty sure it's an Intel Quad core with total of 8 threads. Doesn't matter, how do I make sense of these numbers?
protected double getCPUUtilization5() {
OperatingSystemMXBean osBean =
ManagementFactory.getOperatingSystemMXBean();
if (startSystemAverage == null) {
startSystemAverage = osBean.getSystemLoadAverage();
peakSystemAverage = osBean.getSystemLoadAverage();
}
if (peakSystemAverage < osBean.getSystemLoadAverage()) {
peakSystemAverage = osBean.getSystemLoadAverage();
}
double sysAvg = osBean.getSystemLoadAverage();
logger.info(" getCPUUtilization5: "+ sysAvg + " num of processors: "+ osBean.getAvailableProcessors());
return sysAvg;
}