Prior to Java 1.5, capturing a thread dump required use of JMPI and JNI, pressing control-BREAK in the java console or use of a tool such as the adaptj Stack Trace application. With the new API’s in Java 1.5 (5.0), it is now trivial to programatically capture a thread dump of your java application.
The following method provides a simple way to capture a thread dump of the JVM that this method is executing within.
public static String captureThreadDump() { Map allThreads = Thread.getAllStackTraces(); Iterator iterator = allThreads.keySet().iterator(); StringBuffer stringBuffer = new StringBuffer(); while(iterator.hasNext()) { Thread key = (Thread)iterator.next(); StackTraceElement[] trace = (StackTraceElement[])allThreads.get(key); stringBuffer.append(key+"\r\n"); for(int i = 0; i