001/*
002 * JPPF.
003 * Copyright (C) 2005-2016 JPPF Team.
004 * http://www.jppf.org
005 *
006 * Licensed under the Apache License, Version 2.0 (the "License");
007 * you may not use this file except in compliance with the License.
008 * You may obtain a copy of the License at
009 *
010 *   http://www.apache.org/licenses/LICENSE-2.0
011 *
012 * Unless required by applicable law or agreed to in writing, software
013 * distributed under the License is distributed on an "AS IS" BASIS,
014 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
015 * See the License for the specific language governing permissions and
016 * limitations under the License.
017 */
018
019package org.jppf.management.diagnostics;
020
021import java.io.Serializable;
022import java.lang.management.*;
023import java.util.*;
024
025/**
026 * This class encapsulates a JVM thread dump, including dealocks information when available.
027 * @author Laurent Cohen
028 */
029public class ThreadDump implements Serializable
030{
031  /**
032   * Information on the threads.
033   */
034  private final Map<Long, ThreadInformation> threads;
035  /**
036   * The ids of the deadlocked threads.
037   */
038  private final long[] deadlockedThreads;
039
040  /**
041   * Create this thread dump from the specified thread mxbean.
042   * @param threadMXBean the thread MXBean to get the information from.
043   */
044  public ThreadDump(final ThreadMXBean threadMXBean)
045  {
046    ThreadInfo[] tis = threadMXBean.dumpAllThreads(threadMXBean.isObjectMonitorUsageSupported(), threadMXBean.isSynchronizerUsageSupported());
047    if ((tis == null) || (tis.length <= 0)) threads = null;
048    else
049    {
050      threads = new TreeMap<>();
051      for (ThreadInfo ti: tis) threads.put(ti.getThreadId(), new ThreadInformation(ti));
052    }
053    long[] ids = threadMXBean.isSynchronizerUsageSupported() ? threadMXBean.findDeadlockedThreads() : null;
054    this.deadlockedThreads = (ids == null) || (ids.length <= 0) ? null : ids;
055  }
056
057  /**
058   * Get information on the threads.
059   * @return a mapping of {@link ThreadInformation} objects to their thread id, or <code>null</code> if no thread information is available.
060   */
061  public Map<Long, ThreadInformation> getThreads()
062  {
063    return threads;
064  }
065
066  /**
067   * Get the ids of the deadlock threads, if any.
068   * @return the ids as an array of <code>long</code> values, or <code>null</code> if none exists.
069   */
070  public long[] getDeadlockedThreads()
071  {
072    return deadlockedThreads;
073  }
074
075  @Override
076  public String toString()
077  {
078    return TextThreadDumpWriter.printToString(this, "ThreadDump");
079  }
080}