从 java 代码生成线程转储

Generate thread dump from java code

我有以下方法覆盖 Jenkins 中的默认排序器:

@Override
public void sortBuildableItems(List<Queue.BuildableItem> items) {
    logBuildQueue(items, "BEFORE");
    ExecutorService executorService = Executors.newSingleThreadExecutor();
    Future future =  executorService.submit(new Runnable() {
        @Override public void run() {
            items.sort(CustomSorter::compare);
        }
    });
    try {
        future.get(2, TimeUnit.SECONDS);
    }
    catch (InterruptedException e) {
        LOGGER.log(Level.SEVERE, "[INTERRUPTED EXCEPTION] Message:" + e.getMessage() + " StackTrace: " + Arrays.toString(e.getStackTrace()));
        setDefaultSorter();
        e.printStackTrace();
    }
    catch (ExecutionException e) {
        LOGGER.log(Level.SEVERE, "[EXECUTION EXCEPTION] Message:" + e.getMessage() + " StackTrace: " + Arrays.toString(e.getStackTrace()));
        setDefaultSorter();
        e.printStackTrace();
    }
    catch (TimeoutException e) {
        LOGGER.log(Level.SEVERE, "[TIMEOUT EXCEPTION] Sorting the items took more then 2 seconds, Message:" + e.getMessage() + " StackTrace: " + Arrays.toString(e.getStackTrace()));
        setDefaultSorter();
        e.printStackTrace();
    }

    logBuildQueue(items, "AFTER");
}

我希望打印所有我能得到的信息以防发生异常,我想知道是否有任何方法可以将线程转储推送到日志中,因为错误消息可能不存在。

    public void  dumpThreadDump() {
    ThreadMXBean threadMxBean = ManagementFactory.getThreadMXBean();
    for (ThreadInfo ti : threadMxBean.dumpAllThreads(true, true)) {
        System.out.print(ti.toString());
    }
}

这似乎是一种以编程方式从当前应用程序获取线程转储的好方法。