java 线程采集

ThreadMXBean


一个线程死锁检测的类

/**
 * A utility class for detecting deadlocked threads.
 */
public class ThreadDeadlockDetector {
    private static final int MAX_STACK_TRACE_DEPTH = 100;


    private final ThreadMXBean threads;


    /**
     * Creates a new detector.
     */
    public ThreadDeadlockDetector() {
        this(ManagementFactory.getThreadMXBean());
    }


    /**
     * Creates a new detector using the given {@link ThreadMXBean}.
     *
     * @param threads    a {@link ThreadMXBean}
     */
    public ThreadDeadlockDetector(ThreadMXBean threads) {
        this.threads = threads;
    }


    /**
     * Returns a set of diagnostic stack traces for any deadlocked threads. If no threads are
     * deadlocked, returns an empty set.
     *
     * @return stack traces for deadlocked threads or an empty set
     */
    public Set<String> getDeadlockedThreads() {
        final long[] ids = threads.findDeadlockedThreads();
        if (ids != null) {
            final Set<String> deadlocks = new HashSet<String>();
            for (ThreadInfo info : threads.getThreadInfo(ids, MAX_STACK_TRACE_DEPTH)) {
                final StringBuilder stackTrace = new StringBuilder();
                for (StackTraceElement element : info.getStackTrace()) {
                    stackTrace.append("\t at ")
                              .append(element.toString())
                              .append(String.format("%n"));
                }


                deadlocks.add(
                        String.format("%s locked on %s (owned by %s):%n%s",
                                      info.getThreadName(),
                                      info.getLockName(),
                                      info.getLockOwnerName(),
                                      stackTrace.toString()
                        )
                );
            }
            return Collections.unmodifiableSet(deadlocks);
        }
        return Collections.emptySet();
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值