Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does getSystemCpuLoad() returns negative value

I need to get the CPU usage and memory usage using Java. Found the getSystemCpuLoad() of com.sun.management.OperatingSystemMXBean. According to docs, it returns a value between 0.0 and 1.0. but I am getting -1 always. According to docs, this is returned when the value is not available. But why does it always return negative value. Is there any property which I need to change in order to fetch correct values?

If not, appreciate if someone can suggest any other approach to get CPU usage and memory usage.

My code includes:

OperatingSystemMXBean operatingSystemMXBean = (OperatingSystemMXBean) ManagementFactory.getOperatingSystemMXBean();
System.out.println(operatingSystemMXBean.getSystemCpuLoad());
like image 408
udani Avatar asked Mar 25 '26 17:03

udani


1 Answers

The documentation of com.sun.management.OperatingSystemMXBean really only says that the method returns a negative value if the information could not be accessed for some reason. It could, for example, be so because the data is not yet available or perhaps because you do not have the privilege(s) necessary to retrieve this information.


OperatingSystemMXBean does seem to need a little bit of time to gather data before getSystemCpuLoad starts returning anything useful.

The following code shows how one can test this phenomenon.

OperatingSystemMXBean operatingSystemMXBean = (OperatingSystemMXBean) ManagementFactory.getOperatingSystemMXBean();
long t = System.currentTimeMillis();
while(System.currentTimeMillis() < t + 5000) {
  System.out.println(operatingSystemMXBean.getSystemCpuLoad());
  TimeUnit.SECONDS.sleep(1);
}

Something I have personally experienced is that when this function is being executed as a windows service by a user that is not a member of either the Performance Log Users or the Performance Monitor Users groups, the function will always return -1 since the user does not have the necessary privileges (to make the system calls, which is what is done in the end).

like image 166
ParallelNoob Avatar answered Mar 27 '26 06:03

ParallelNoob



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!