Wednesday, April 01, 2009

Thread wise CPU monitoring for Java process

We come across many occations where java application is hung or slow with high CPU usage. We want to analyze which thread is causing this high CPU usage.
Java 1.5 provides a API "ThreadMXBean.getThreadCPUTime()"
We can use the following code in anywhere in the JVM to get the thread wise CPU usage of that JVM.
ThreadMXBean threads = ManagementFactory.getThreadMXBean();
ThreadInfo[] threadInfos = threads.getThreadInfo( threads.getAllThreadIds() );
for( int i=0; i < threadInfos.length; i++ )
long cpuTimeCumulative = threads.getThreadCpuTime( threadInfos[ i ].getThreadId() ); // in nano seconds
There is a utility called JTop available with JDK 1.6 (JDK_insall_dir/demo/management/JTop). This can be invoked as a JConsole plugin as well.
You can invoke the JConsole with plugin as follows:
/bin/jConsole.exe -pluginpath
eg: c:/jdk160/bin/jConsole.exe -pluginpath c:/jdk160/demo/management/JTop/JTop.jar
The default JTop shows only the cumulative CPU time (not the current CPU usage as if in Task manager).
I have modified the JTop little bit to include the current CPU usage as well.
You can download the modified JTop.jar from the following path.
This will help us to identify the threads causing high CPU. Typically this will help us to resolve infinite loop issues.


libre said...

Hi Rejeev,
I noticed that you use JMX extensively. How much in your experience is the overhead in using JMX for monitoring compared to using a socket in a seperate thread when we intend to use a custom functionality?

Chris said...


Very interresting post.

I've successfully installed and used the JTop.jar that you mention above. However, I do not manage to reproduce the same percentage values from my own ThreadMXBean bean instance :
=> one difference that I can see is that I am running it "locally" whereas Jconsole is run "remotely

In my case, I unfortunately have to use the local manner ; would you be aware about any problem when monitoring our Java process locally ?

Any help being very appreciated,


Onkar Joshi said...
This comment has been removed by the author.
Onkar Joshi said...

Thanks for this tip about using JTop! It saved me quite a bit of botheration!


Mosh said...


The jtop.jar is very useful.