Java JMX API provides you some useful classes to find out details about your JVM. One of those classes is ManagementFactory, This class provides API to find meta data about the JVM. In the below given example we will find all the live threads in the JVM and its state.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 |
package com.ourownjava.corejava.thread; import java.lang.management.ManagementFactory; import java.lang.management.ThreadInfo; /** * @author ourownjava.com * @date 28th June, 2011 * * Example program to find all live threads in your JVM instance. * */ public class ManagementFactoryExample { public static void main(final String args[]){ final WorkerThread worker = new WorkerThread(); worker.setName("workerThread"); worker.start(); final ThreadInfo[] threadInfos = ManagementFactory.getThreadMXBean(). getThreadInfo(ManagementFactory.getThreadMXBean().getAllThreadIds()); for(final ThreadInfo threadInfo : threadInfos){ System.out.println(threadInfo.getThreadId()); System.out.println(threadInfo.getThreadName()); System.out.println(threadInfo.getThreadState()); } System.out.println("Total number of live threads :"+ManagementFactory.getThreadMXBean().getThreadCount()); } } class WorkerThread extends Thread{ public void run(){ try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } } |
Console output.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
/mnt/opt/java com.ourownjava.corejava.thread.ManagementFactoryExample 8 workerThread TIMED_WAITING 5 Attach Listener RUNNABLE 4 Signal Dispatcher RUNNABLE 3 Finalizer WAITING 2 Reference Handler WAITING 1 main RUNNABLE Total number of live threads :6 |