Example of ThreadMXBean in Java
March 25, 2013
ThreadMXBean belongs to the package java.lang.management. ThreadMXBean gives the information about threads in JVM. The object of ThreadMXBean is obtained as
ThreadMXBean thMxB = ManagementFactory.getThreadMXBean();
ThreadMXBeanTest.java
package com.concretepage; import java.lang.management.ManagementFactory; import java.lang.management.ThreadMXBean; public class ThreadMXBeanTest { class UserThread extends Thread { @Override public void run() { ThreadMXBean thMxB = ManagementFactory.getThreadMXBean(); System.out.println(("Current thread count:"+ thMxB.getThreadCount())); //gets current thread cpu time. System.out.println("CurrentThreadCpuTime: "+thMxB.getCurrentThreadCpuTime()); //gets curent thread user time. System.out.println("CurrentThreadUserTime:"+thMxB.getCurrentThreadUserTime()); //gets Demon thread count System.out.println("DaemonThreadCount:"+thMxB.getDaemonThreadCount()); //gets peaak thread count System.out.println("PeakThreadCount:"+thMxB.getPeakThreadCount()); //gets thread count System.out.println("ThreadCount:"+thMxB.getThreadCount()); } } public static void main(String[] a){ Thread th= new ThreadMXBeanTest().new UserThread(); Runtime.getRuntime().addShutdownHook(th); } }
Current thread count:6 CurrentThreadCpuTime: 0 CurrentThreadUserTime:0 DaemonThreadCount:4 PeakThreadCount:6 ThreadCount:6