Using OperatingSystemMXBean to use CPU

I am trying to use Java to get the percentage of processor used by the current Java virtual machine. In my research, I pointed to the use of the com.sun.management.OperatingSystemMXBean class. The following examples on the Internet I wrote the following:

 import java.lang.management.ManagementFactory; import com.sun.management.OperatingSystemMXBean; public class TestClass { public static void main (String[] args) { OperatingSystemMXBean bean = (com.sun.management.OperatingSystemMXBean) ManagementFactory.getOperatingSystemMXBean(); System.out.println(bean.getProcessCpuLoad()); System.out.println(bean.getSystemCpuLoad()); } } 

After testing this on two machines, I can't stop getting a -1.0 result for both calls. I tried to run this code using 64- and 32-bit versions of Java 7 and 6 using various methods. However, all I get is a listing from -1.0 , which according to Javadocs ,

All values betweens 0.0 and 1.0 are possible depending of the activities going on in the system. If the system recent cpu usage is not available, the method returns a negative value.

I do not know what else to do here. Getting the processor load is critical, and I would like to avoid using another library like Sigar. Anyone have any recommendations or have any ideas on this issue?

+7
java cpu
source share
1 answer

Just answering my question if he can help someone.

What I did was technically correct, but I did not give OperatingSystemMXBean enough time to collect information about CPU usage. In fact, the JVM must run for a few seconds before it can collect CPU usage information, and then the resolution of the update is implementation dependent.

Running the code with the following change will start showing 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()); } } 

Hope this can help someone

+21
source share

All Articles