Example #1
0
  /**
   * Retrieve a JVM thread dump formatted using the given StringManager.
   *
   * @param requestedSm the StringManager to use
   * @return the formatted JVM thread dump
   */
  private static String getThreadDump(StringManager requestedSm) {
    StringBuilder sb = new StringBuilder();

    synchronized (timeformat) {
      sb.append(timeformat.format(new Date()));
    }
    sb.append(CRLF);

    sb.append(requestedSm.getString("diagnostics.threadDumpTitle"));
    sb.append(" ");
    sb.append(runtimeMXBean.getVmName());
    sb.append(" (");
    sb.append(runtimeMXBean.getVmVersion());
    String vminfo = System.getProperty(vminfoSystemProperty);
    if (vminfo != null) {
      sb.append(" " + vminfo);
    }
    sb.append("):" + CRLF);
    sb.append(CRLF);

    ThreadInfo[] tis = threadMXBean.dumpAllThreads(true, true);
    sb.append(getThreadDump(tis));

    sb.append(findDeadlock());
    return sb.toString();
  }
Example #2
0
 @RequestMapping("/dumpThead")
 @ResponseBody
 public void doDumpThread(HttpServletRequest request, HttpServletResponse response) {
   try {
     String app = request.getParameter("app");
     String threadId = request.getParameter("threadId");
     ThreadMXBean tBean = JMConnManager.getThreadMBean(app);
     JSONObject data = new JSONObject();
     if (threadId != null) {
       Long id = Long.valueOf(threadId);
       ThreadInfo threadInfo = tBean.getThreadInfo(id, Integer.MAX_VALUE);
       data.put("info", threadInfo.toString());
     } else {
       ThreadInfo[] dumpAllThreads = tBean.dumpAllThreads(false, false);
       StringBuffer info = new StringBuffer();
       for (ThreadInfo threadInfo : dumpAllThreads) {
         info.append("\n").append(threadInfo);
       }
       data.put("info", info);
     }
     writeFile(request, response, data);
   } catch (IOException e) {
     throw new RuntimeException(e);
   }
 }
Example #3
0
  public static void main(String[] args) {
    // 获取Java线程管理MXBean
    ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean();

    ThreadInfo[] threadInfos = threadMXBean.dumpAllThreads(false, false);
    for (ThreadInfo threadInfo : threadInfos) {
      System.out.println("[" + threadInfo.getThreadId() + " ] " + threadInfo.getThreadName());
    }
  }
Example #4
0
  public static CharSequence getThreadStats(
      boolean lockedMonitors, boolean lockedSynchronizers, boolean stackTrace) {
    StringBuilder list = new StringBuilder();

    int threadCount = threadMXbean.getThreadCount();
    int daemonCount = threadMXbean.getThreadCount();
    int nonDaemonCount = threadCount - daemonCount;
    int peakCount = threadMXbean.getPeakThreadCount();
    long totalCount = threadMXbean.getTotalStartedThreadCount();

    list.append("Live: .................... ").append(threadCount).append(" threads").append("\n");
    list.append("     Non-Daemon: ......... ")
        .append(nonDaemonCount)
        .append(" threads")
        .append("\n");
    list.append("     Daemon: ............. ").append(daemonCount).append(" threads").append("\n");
    list.append("Peak: .................... ").append(peakCount).append(" threads").append("\n");
    list.append("Total started: ........... ").append(totalCount).append(" threads").append("\n");
    list.append("=================================================").append("\n");

    for (ThreadInfo info : threadMXbean.dumpAllThreads(lockedMonitors, lockedSynchronizers)) {
      list.append("Thread #")
          .append(info.getThreadId())
          .append(" (")
          .append(info.getThreadName())
          .append(")")
          .append("\n");
      list.append("=================================================\n");
      list.append("\tgetThreadState: ...... ").append(info.getThreadState()).append("\n");
      list.append("\tgetWaitedTime: ....... ").append(info.getWaitedTime()).append("\n");
      list.append("\tgetBlockedTime: ...... ").append(info.getBlockedTime()).append("\n");
      for (MonitorInfo monitorInfo : info.getLockedMonitors()) {
        list.append("\tLocked monitor: ....... ").append(monitorInfo).append("\n");
        list.append("\t\t[")
            .append(monitorInfo.getLockedStackDepth())
            .append(".]: at ")
            .append(monitorInfo.getLockedStackFrame())
            .append("\n");
      }

      for (LockInfo lockInfo : info.getLockedSynchronizers()) {
        list.append("\tLocked synchronizer: ...").append(lockInfo).append("\n");
      }
      if (stackTrace) {
        list.append("\tgetStackTace: ..........\n");
        for (StackTraceElement trace : info.getStackTrace())
          list.append("\t\tat ").append(trace).append("\n");
      }
      list.append("=================================================\n");
    }

    return list;
  }
Example #5
0
  public static void main(String[] argv) throws Exception {
    mbean = newPlatformMXBeanProxy(server, THREAD_MXBEAN_NAME, ThreadMXBean.class);

    if (!mbean.isSynchronizerUsageSupported()) {
      System.out.println("Monitoring of synchronizer usage not supported");
      return;
    }

    thread.setDaemon(true);
    thread.start();

    // wait until myThread acquires mutex and lock owner is set.
    while (!(mutex.isLocked() && mutex.getLockOwner() == thread)) {
      try {
        Thread.sleep(100);
      } catch (InterruptedException e) {
        throw new RuntimeException(e);
      }
    }

    long[] ids = new long[] {thread.getId()};

    // validate the local access
    ThreadInfo[] infos = getThreadMXBean().getThreadInfo(ids, true, true);
    if (infos.length != 1) {
      throw new RuntimeException(
          "Returned ThreadInfo[] of length=" + infos.length + ". Expected to be 1.");
    }
    thread.checkThreadInfo(infos[0]);

    // validate the remote access
    infos = mbean.getThreadInfo(ids, true, true);
    if (infos.length != 1) {
      throw new RuntimeException(
          "Returned ThreadInfo[] of length=" + infos.length + ". Expected to be 1.");
    }
    thread.checkThreadInfo(infos[0]);

    boolean found = false;
    infos = mbean.dumpAllThreads(true, true);
    for (ThreadInfo ti : infos) {
      if (ti.getThreadId() == thread.getId()) {
        thread.checkThreadInfo(ti);
        found = true;
      }
    }

    if (!found) {
      throw new RuntimeException("No ThreadInfo found for MyThread");
    }

    System.out.println("Test passed");
  }
Example #6
0
  @Before
  public void setUp() throws Exception {
    final StackTraceElement rLine1 = new StackTraceElement("Blah", "blee", "Blah.java", 100);

    when(runnable.getThreadName()).thenReturn("runnable");
    when(runnable.getThreadId()).thenReturn(100L);
    when(runnable.getThreadState()).thenReturn(Thread.State.RUNNABLE);
    when(runnable.getStackTrace()).thenReturn(new StackTraceElement[] {rLine1});
    when(runnable.getLockedMonitors()).thenReturn(new MonitorInfo[] {});
    when(runnable.getLockedSynchronizers()).thenReturn(new LockInfo[] {});

    when(threadMXBean.dumpAllThreads(true, true)).thenReturn(new ThreadInfo[] {runnable});
  }
Example #7
0
 private String threadDumpDescription() {
   StringBuilder threadDumpDescription = new StringBuilder();
   ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean();
   ThreadInfo[] threadInfos = threadMXBean.dumpAllThreads(true, true);
   for (ThreadInfo threadInfo : threadInfos) {
     threadDumpDescription.append(
         format(
             "\"%s\"%n\tjava.lang.Thread.State: %s",
             threadInfo.getThreadName(), threadInfo.getThreadState()));
     for (StackTraceElement stackTraceElement : threadInfo.getStackTrace()) {
       threadDumpDescription.append(LINE_SEPARATOR + "\t\tat " + stackTraceElement);
     }
     threadDumpDescription.append(LINE_SEPARATOR + LINE_SEPARATOR);
   }
   return threadDumpDescription.toString();
 }
Example #8
0
  @RequestMapping("/loadThreadInfo")
  @ResponseBody
  public JSONObject doLoadThreadInfo(HttpServletRequest request) {
    try {
      String app = request.getParameter("app");
      ThreadMXBean tBean = JMConnManager.getThreadMBean(app);
      ThreadInfo[] allThreads = tBean.dumpAllThreads(false, false);

      JSONObject root = new JSONObject();
      JSONArray detail = new JSONArray();
      HashMap<State, Integer> state = new HashMap<Thread.State, Integer>();
      for (ThreadInfo info : allThreads) {
        JSONObject th = new JSONObject();
        long threadId = info.getThreadId();
        long cpu = tBean.getThreadCpuTime(threadId);
        State tState = info.getThreadState();

        th.put("id", threadId);
        th.put("state", tState);
        th.put("name", info.getThreadName());
        th.put("cpu", TimeUnit.NANOSECONDS.toMillis(cpu));
        detail.add(th);

        Integer vl = state.get(tState);
        if (vl == null) {
          state.put(tState, 0);
        } else {
          state.put(tState, vl + 1);
        }
      }

      root.put("state", state);
      root.put("detail", detail);
      root.put("total", tBean.getThreadCount());
      root.put("time", System.currentTimeMillis());
      root.put("deamon", tBean.getDaemonThreadCount());

      return root;
    } catch (IOException e) {
      throw new RuntimeException(e);
    }
  }
  /**
   * Collect all of the dependencies that exist between threads in this VM, using java management
   * beans and the {@link DependencyMonitor}.
   *
   * <p>Threads may depend on locks, or on other resources that are tracked by the {@link
   * DependencyMonitor}.
   *
   * @arg locality a name tag to stick on entities to help associate them with this JVM and
   *     distinguish them from entities from other jvms
   * @return All of the dependencies between threads and locks or other resources on this VM.
   */
  public static Set<Dependency> collectAllDependencies(Serializable locality) {
    ThreadMXBean bean = ManagementFactory.getThreadMXBean();
    ThreadInfo[] infos = bean.dumpAllThreads(true, true);

    Set<Dependency> results = new HashSet<Dependency>();

    Map<Long, ThreadInfo> threadInfos = new HashMap<Long, ThreadInfo>();
    for (ThreadInfo info : infos) {
      // This can happen if the thread died.
      if (info == null) {
        continue;
      }

      for (LockInfo monitor : info.getLockedMonitors()) {
        Dependency dependency =
            new Dependency(new LocalLockInfo(locality, monitor), new LocalThread(locality, info));
        results.add(dependency);
      }

      for (LockInfo sync : info.getLockedSynchronizers()) {
        Dependency dependency =
            new Dependency(new LocalLockInfo(locality, sync), new LocalThread(locality, info));
        results.add(dependency);
      }

      LockInfo waitingFor = info.getLockInfo();
      if (waitingFor != null) {
        Dependency dependency =
            new Dependency(
                new LocalThread(locality, info), new LocalLockInfo(locality, waitingFor));
        results.add(dependency);
      }

      threadInfos.put(info.getThreadId(), info);
    }

    Set<Dependency> monitoredDependencies =
        collectFromDependencyMonitor(bean, locality, threadInfos);
    results.addAll(monitoredDependencies);
    return results;
  }
  protected String generateThreadDump() {
    StringBuilder dump = new StringBuilder();
    ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean();
    ThreadInfo[] threadInfos = threadMXBean.dumpAllThreads(true, true);
    long currentThreadId = Thread.currentThread().getId();
    for (ThreadInfo threadInfo : threadInfos) {
      long threadId = threadInfo.getThreadId();
      if (threadId == currentThreadId) {
        continue;
      }
      dump.append('"');
      dump.append(threadInfo.getThreadName());
      dump.append("\" ");

      Thread.State state = threadInfo.getThreadState();
      dump.append("\n\tjava.lang.Thread.State: ");
      dump.append(state);
      if (threadInfo.getLockName() != null) {
        dump.append(", on lock=").append(threadInfo.getLockName());
      }
      if (threadInfo.getLockOwnerName() != null) {
        dump.append(", owned by ").append(threadInfo.getLockOwnerName());
        dump.append(", id=").append(threadInfo.getLockOwnerId());
      }
      if (THREAD_CPU_TIME_INFO_AVAILABLE) {
        dump.append(", cpu=").append(threadMXBean.getThreadCpuTime(threadId)).append(" nsecs");
        dump.append(", usr="******" nsecs");
      }
      if (THREAD_CONTENTION_INFO_AVAILABLE) {
        dump.append(", blocked=").append(threadInfo.getBlockedTime()).append(" msecs");
        dump.append(", waited=").append(threadInfo.getWaitedTime()).append(" msecs");
      }
      StackTraceElement[] stackTraceElements = threadInfo.getStackTrace();
      for (StackTraceElement stackTraceElement : stackTraceElements) {
        dump.append("\n\t\tat ");
        dump.append(stackTraceElement);
      }
      dump.append("\n\n");
    }
    return dump.toString();
  }
Example #11
0
  private static void dumpThreadInfo(
      StringBuilder threadDump, boolean withLocks, ThreadMXBean threadMx) {
    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    String timestamp = dateFormat.format(new Date());
    threadDump.append(timestamp);
    threadDump.append("\nFull thread dump ");
    threadDump.append("\n");

    if (withLocks) {
      ThreadInfo[] threadInfos = threadMx.dumpAllThreads(true, true);
      for (ThreadInfo threadInfo : threadInfos) {
        printThreadInfo(threadInfo, threadDump);
        LockInfo[] syncs = threadInfo.getLockedSynchronizers();
        printLockInfo(syncs, threadDump);
      }
      threadDump.append("\n");
    } else {
      long[] threadIds = threadMx.getAllThreadIds();
      ThreadInfo[] threadInfos = threadMx.getThreadInfo(threadIds, Integer.MAX_VALUE);
      for (ThreadInfo threadInfo : threadInfos) printThreadInfo(threadInfo, threadDump);
    }
  }
Example #12
0
 public List<ThreadInfo> getThreadDump() {
   return Arrays.asList(threadMXBean.dumpAllThreads(dumpLockedMonitors, dumpLockedSynchronizers));
 }