2008-08-04

Monitoring java threads programmatically

Using the java.lang.management package introduced in java 1.5 one may monitor some aspects of the threads of a java process:
  • Find all active threads and get their stack traces
  • Find deadlocked threads
  • Find out what lock a thread is waiting for (and which thread owns it)
  • (Optional, depending on JVM): Monitor thread contention - how many times and for how long have each thread waited or blocked
  • (Optional, depending on JVM): Measure thread CPU time (and how much of that time was spent in user mode)
The code to do this looks as follows:
ThreadMXBean threadBean = ManagementFactory.getThreadMXBean();
if (threadBean.isThreadCpuTimeSupported())
threadBean.setThreadCpuTimeSupported(true);
if (threadBean.isThreadContentionMonitoringSupported())
threadBean.setThreadContentionMonitoringEnabled(true);

out.println("There are " + threadBean.getThreadCount() +
" threads of which " + threadBean.getDaemonThreadCount() +
" are daemons.");

ThreadInfo[] infos
= threadBean.getThreadInfo(threadBean.getAllThreadIds(), Integer.MAX_VALUE);

for (ThreadInfo info : infos) {
out.println("Thread(id=" + info.getThreadId() + "): " +
info.getThreadName() + ":");

out.println("\tState: " + info.getThreadState());
if (info.getLockOwnerId() != null)
out.println("\tWaiting on lock " + info.getLockName() + " owned by " + info.getLockOwnerId());

if (info.getBlockedTime() != -1) {
out.println("\tBlocked time: " + (info.getBlockedTime() / 1000.) + " seconds during " +
info.getBlockedCount() + " blocks");
out.println("\tWaited time: " + (info.getWaitedTime() / 1000.) + " seconds during " +
info.getWaitedCount() + " blocks");
}

out.println("\tStack trace:");
for (int j = 0; j < threadInfo.getStackTrace().length; j++) {
StackTraceElement e = threadInfo.getStackTrace()[j];
out.println(e.getClassName() + "#" + e.getMethodName() + ":" + e.getLineNumber());
}
}

1 comment:

Anonymous said...

I found a good link explaining Java interview question & Answer

Core Java faqs, questions & answers