Java tutorial
//package com.java2s; //License from project: Apache License import java.lang.management.LockInfo; import java.lang.management.ManagementFactory; import java.lang.management.MonitorInfo; import java.lang.management.ThreadInfo; import java.lang.management.ThreadMXBean; import java.lang.reflect.Array; import java.util.ArrayList; import java.util.List; public class Main { public static String[] getStackTrace(long threadID) { ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean(); ThreadInfo threadInfo = threadMXBean.getThreadInfo(threadID, Integer.MAX_VALUE); List<String> buf = new ArrayList<String>(); if (threadInfo == null) { return buf.toArray((String[]) Array.newInstance(String.class, buf.size())); } StackTraceElement[] stackTrace = threadInfo.getStackTrace(); for (int i = 0; i < stackTrace.length; i++) { StackTraceElement ste = stackTrace[i]; buf.add("\t" + ste.toString()); if (i == 0 && threadInfo.getLockInfo() != null) { Thread.State ts = threadInfo.getThreadState(); switch (ts) { case BLOCKED: buf.add("\t- blocked on " + threadInfo.getLockInfo()); break; case WAITING: buf.add("\t- waiting on " + threadInfo.getLockInfo()); break; case TIMED_WAITING: buf.add("\t- waiting on " + threadInfo.getLockInfo()); break; default: } } for (MonitorInfo mi : threadInfo.getLockedMonitors()) { if (mi.getLockedStackDepth() == i) { buf.add("\t- locked " + mi); } } } LockInfo[] locks = threadInfo.getLockedSynchronizers(); if (locks.length > 0) { buf.add("\n\tNumber of locked synchronizers = " + locks.length); for (LockInfo li : locks) { buf.add("\t- " + li); } } return buf.toArray((String[]) Array.newInstance(String.class, buf.size())); } }