measure CPU usage of the JVM : java code

nadh picture nadh · May 6, 2011 · Viewed 29.8k times · Source

Is there a way to measure CPU usage of the JVM (once a java application is started) cross platform (windows + unix + mac)? I have used Jconsole but what I need is a java code that does this, and not a tool through which I can monitor CPU utilization. I have tried out

ManagementFactory.getOperatingSystemMXBean().getSystemLoadAverage()

using JMX, but it doesn't help since what I need is the specific CPU usage by the JVM (say when I start a server), not the system load average.

Answer

Thomas Jung picture Thomas Jung · May 6, 2011

You should have a look at the ThreadMXBean.getThreadCPUTime() method from the Thread MBean.

Thread CPU time

A Java virtual machine implementation may support measuring the CPU time for the current thread, for any thread, or for no threads.

There is also the JTop sample application that's part of the JDK jdk\demo\management\JTop\src\JTop.java or here. Have a look at:

/**
 * Get the thread list with CPU consumption and the ThreadInfo for each thread
 * sorted by the CPU time.
 */
private List<Map.Entry<Long, ThreadInfo>> getThreadList()