This is a solution to a problem, occurred to me while developing Depli a JVM monitoring dashboard which uses JMX remote connections.
There is no way to get the JVM CPU usage directly using MXBeans in JDKs older than version 7. For my application I wanted a universal method.
Finally, I got it working thanks to source code of jconsole.
Ideal solution to calculate CPU usage is periodically look at the idle time and get the time that JVM is not idle.
But there is no method to expose idle time in MXBeans. So here, JVM CPU usage is calculated using getting the
ratio of how much discrete time slices JVM used and how long JVM was up while using those time slices(total JVM uptime in all the available threads for JVM),
in a particular time period. Below algorithm will explain it better.
Get it working
We will be using remote method invocation(RMI) to connect and call methods in remote MXBean interfaces.
First we have to connect to a JMX remote connection and have to initiate a managed beans server connection.
Now we can create proxy connections to MXBean interfaces to forward method calls though the managed bean server
connection that we have created above. We will be using runtime MXBean, operating system MXBean and operating system
MXBean from platform extension.
We can call the appropriate methods to get required data now. We need data on how long JVM processes used the CPU, JVM uptime and
how much processors allowed for the JVM in a paticular time period.
Now we can get JVM CPU usage by calling the getJvmCpuUsage periodically. You can obtain the complete Java code from this Gist.
I am a software developer from Colombo, Sri Lanka who believes in following good design and good engineering aspects when developing software thus they play the major role when bringing high-quality software products into reality. I have been working professionally since 2015 a year as a DevOps engineer and afterward as a software developer.