001package org.cache2k.impl.util;
002
003/*
004 * #%L
005 * cache2k core package
006 * %%
007 * Copyright (C) 2000 - 2015 headissue GmbH, Munich
008 * %%
009 * This program is free software: you can redistribute it and/or modify
010 * it under the terms of the GNU General Public License as
011 * published by the Free Software Foundation, either version 3 of the 
012 * License, or (at your option) any later version.
013 * 
014 * This program is distributed in the hope that it will be useful,
015 * but WITHOUT ANY WARRANTY; without even the implied warranty of
016 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
017 * GNU General Public License for more details.
018 * 
019 * You should have received a copy of the GNU General Public 
020 * License along with this program.  If not, see
021 * <http://www.gnu.org/licenses/gpl-3.0.html>.
022 * #L%
023 */
024
025import java.lang.management.ManagementFactory;
026import java.lang.management.ThreadInfo;
027import java.lang.management.ThreadMXBean;
028
029/**
030 * Thread dump generation, inspired from: http://crunchify.com/how-to-generate-java-thread-dump-programmatically/
031 *
032 * @author Jens Wilke; created: 2014-09-13
033 */
034public class ThreadDump {
035
036  public static String generateThredDump() {
037    final StringBuilder sb = new StringBuilder();
038    final ThreadMXBean _threadMXBean = ManagementFactory.getThreadMXBean();
039    final ThreadInfo[] _infos =
040      _threadMXBean.getThreadInfo(_threadMXBean.getAllThreadIds(), Integer.MAX_VALUE);
041    for (ThreadInfo _info : _infos) {
042      sb.append("Thread \"");
043      sb.append(_info.getThreadName());
044      sb.append("\" ");
045      final Thread.State _state = _info.getThreadState();
046      sb.append(_state);
047      final StackTraceElement[] stackTraceElements = _info.getStackTrace();
048      for (final StackTraceElement stackTraceElement : stackTraceElements) {
049        sb.append("\n    at ");
050        sb.append(stackTraceElement);
051      }
052      sb.append("\n\n");
053    }
054    return sb.toString();
055  }
056
057}