Java Code Examples for java.lang.management.ThreadMXBean#dumpAllThreads()

The following examples show how to use java.lang.management.ThreadMXBean#dumpAllThreads() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ManagementFactoryTest.java    From banyan with MIT License 6 votes vote down vote up
public static void main(String[] args) {
    ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean();
    List<GarbageCollectorMXBean> garbageCollectorMXBeanList = ManagementFactory.getGarbageCollectorMXBeans();

    for (GarbageCollectorMXBean gcMXBean : garbageCollectorMXBeanList) {
        String gcName = gcMXBean.getName();
        String memoryPoolNames[] = gcMXBean.getMemoryPoolNames();
        for (String memoryPoolName : memoryPoolNames) {
            System.out.println(memoryPoolName);
        }
        ObjectName objectName = gcMXBean.getObjectName();
        String domainName = objectName.getDomain();
        System.out.println(domainName+"__"+objectName.getCanonicalName());
        System.out.println(gcName);

    }

    //不需要获取同步的monitor 和 synchronize信息,仅获取线程和线程堆栈信息。
    ThreadInfo[] allThreads = threadMXBean.dumpAllThreads(true, true);
    for (ThreadInfo threadInfo : allThreads) {
        String threadName = threadInfo.getThreadName();
        long threadId = threadInfo.getThreadId();
        System.out.println(threadName + "," + threadId + "," + threadInfo.getLockOwnerName());
    }
}
 
Example 2
Source File: AutoScalerPolicyTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
public static void dumpThreadsEtc() {
    ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean();
    ThreadInfo[] threads = threadMXBean.dumpAllThreads(true, true);
    for (ThreadInfo thread : threads) {
        System.out.println(thread.getThreadName()+" ("+thread.getThreadState()+")");
        for (StackTraceElement stackTraceElement : thread.getStackTrace()) {
            System.out.println("\t"+stackTraceElement);
        }
    }
    
    MemoryMXBean memoryMXBean = ManagementFactory.getMemoryMXBean();
    MemoryUsage heapMemoryUsage = memoryMXBean.getHeapMemoryUsage();
    MemoryUsage nonHeapMemoryUsage = memoryMXBean.getNonHeapMemoryUsage();
    System.out.println("Memory:");
    System.out.println("\tHeap: used="+heapMemoryUsage.getUsed()+"; max="+heapMemoryUsage.getMax()+"; init="+heapMemoryUsage.getInit()+"; committed="+heapMemoryUsage.getCommitted());
    System.out.println("\tNon-heap: used="+nonHeapMemoryUsage.getUsed()+"; max="+nonHeapMemoryUsage.getMax()+"; init="+nonHeapMemoryUsage.getInit()+"; committed="+nonHeapMemoryUsage.getCommitted());

    OperatingSystemMXBean operatingSystemMXBean = ManagementFactory.getOperatingSystemMXBean();
    System.out.println("OS:");
    System.out.println("\tsysLoadAvg="+operatingSystemMXBean.getSystemLoadAverage()+"; availableProcessors="+operatingSystemMXBean.getAvailableProcessors()+"; arch="+operatingSystemMXBean.getArch());
}
 
Example 3
Source File: StartStopSshDriverTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
private List<ThreadInfo> getThreadsCalling(Class<?> clazz) {
    String clazzName = clazz.getCanonicalName();
    List<ThreadInfo> result = MutableList.of();
    ThreadMXBean threadMxbean = ManagementFactory.getThreadMXBean();
    ThreadInfo[] threads = threadMxbean.dumpAllThreads(false, false);
    
    for (ThreadInfo thread : threads) {
        StackTraceElement[] stackTrace = thread.getStackTrace();
        for (StackTraceElement stackTraceElement : stackTrace) {
            if (clazzName == stackTraceElement.getClassName()) {
                result.add(thread);
                break;
            }
        }
    }
    return result;
}
 
Example 4
Source File: AbstractContainer.java    From qpid-broker-j with Apache License 2.0 6 votes vote down vote up
public Content findThreadStackTraces(String threadNameFindExpression)
{
    getEventLogger().message(BrokerMessages.OPERATION("findThreadStackTraces"));
    ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean();
    ThreadInfo[] threadInfos = threadMXBean.dumpAllThreads(true, true);
    StringBuilder threadDump = new StringBuilder();
    threadDump.append(String.format("Thread dump (names matching '%s') captured %s",
                                    threadNameFindExpression,
                                    Instant.now())).append(System.lineSeparator());

    Pattern pattern = threadNameFindExpression == null || threadNameFindExpression.equals("") ? null : Pattern.compile(
            threadNameFindExpression);
    for (ThreadInfo threadInfo : threadInfos)
    {
        if (pattern == null || pattern.matcher(threadInfo.getThreadName()).find())
        {
            threadDump.append(getThreadStackTraces(threadInfo));
        }
    }
    return new ThreadStackContent(threadDump.toString());
}
 
Example 5
Source File: AdminResource.java    From datacollector with Apache License 2.0 6 votes vote down vote up
@GET
@Path("/threads")
@ApiOperation(value = "Returns Thread Dump along with stack trace", response = Map.class, responseContainer = "List",
  authorizations = @Authorization(value = "basic"))
@Produces(MediaType.APPLICATION_JSON)
@RolesAllowed({AuthzRole.ADMIN, AuthzRole.ADMIN_REMOTE})
public Response getThreadsDump() throws IOException {
  ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean();
  ThreadInfo[] threads = threadMXBean.dumpAllThreads(true, true);
  List<Map> augmented = new ArrayList<>(threads.length);
  for (ThreadInfo thread : threads) {
    Map<String, Object> map = new LinkedHashMap<>();
    map.put("threadInfo", thread);
    map.put("userTimeNanosecs", threadMXBean.getThreadUserTime(thread.getThreadId()));
    map.put("cpuTimeNanosecs", threadMXBean.getThreadCpuTime(thread.getThreadId()));
    augmented.add(map);
  }
  return Response.ok(augmented).build();
}
 
Example 6
Source File: ConcurrentAssociateTest.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * A debugging tool to print stack traces of most threads, as jstack does.
 * Uninteresting threads are filtered out.
 */
static void dumpTestThreads() {
    ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean();
    System.err.println("------ stacktrace dump start ------");
    for (ThreadInfo info : threadMXBean.dumpAllThreads(true, true)) {
        String name = info.getThreadName();
        if ("Signal Dispatcher".equals(name))
            continue;
        if ("Reference Handler".equals(name)
            && info.getLockName().startsWith("java.lang.ref.Reference$Lock"))
            continue;
        if ("Finalizer".equals(name)
            && info.getLockName().startsWith("java.lang.ref.ReferenceQueue$Lock"))
            continue;
        System.err.print(info);
    }
    System.err.println("------ stacktrace dump end ------");
}
 
Example 7
Source File: JSR166TestCase.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * A debugging tool to print stack traces of most threads, as jstack does.
 * Uninteresting threads are filtered out.
 */
static void dumpTestThreads() {
    SecurityManager sm = System.getSecurityManager();
    if (sm != null) {
        try {
            System.setSecurityManager(null);
        } catch (SecurityException giveUp) {
            return;
        }
    }

    ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean();
    System.err.println("------ stacktrace dump start ------");
    for (ThreadInfo info : threadMXBean.dumpAllThreads(true, true)) {
        final String name = info.getThreadName();
        String lockName;
        if ("Signal Dispatcher".equals(name))
            continue;
        if ("Reference Handler".equals(name)
            && (lockName = info.getLockName()) != null
            && lockName.startsWith("java.lang.ref.Reference$Lock"))
            continue;
        if ("Finalizer".equals(name)
            && (lockName = info.getLockName()) != null
            && lockName.startsWith("java.lang.ref.ReferenceQueue$Lock"))
            continue;
        if ("checkForWedgedTest".equals(name))
            continue;
        System.err.print(info);
    }
    System.err.println("------ stacktrace dump end ------");

    if (sm != null) System.setSecurityManager(sm);
}
 
Example 8
Source File: SystemInfo.java    From boubei-tss with Apache License 2.0 5 votes vote down vote up
@RequestMapping(value = "/test", method = RequestMethod.GET)
@ResponseBody
public Object[] getThreadInfos() {
	ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean();
	ThreadInfo[] threadInfos = threadMXBean.dumpAllThreads(true, true);  
	Long random = null;
	try {
		random = SecureRandom.getInstance("SHA1PRNG").nextLong();
	} catch (NoSuchAlgorithmException e) {
	}
	return new Object[] { threadMXBean.getThreadCount(), threadInfos, random };
}
 
Example 9
Source File: SysUtil.java    From game-server with MIT License 5 votes vote down vote up
/**
 * 线程信息
 * @author JiangZhiYong
 * @QQ 359135103
 * 2017年10月12日 下午5:21:19
 * @param spliteStr
 * @return
 */
public static String threadInfo(String spliteStr) {
	ThreadMXBean bean=ManagementFactory.getThreadMXBean();
	StringBuilder sb = new StringBuilder();
	ThreadInfo[] threads = bean.dumpAllThreads(false, false);
	for(ThreadInfo thread:threads) {
		sb.append("线程信息:   ").append(thread).append(spliteStr);
	}
	sb.append("活动守护线程数目:   ").append(bean.getDaemonThreadCount()).append(spliteStr);
	sb.append("峰值线程数:   ").append(bean.getPeakThreadCount()).append(spliteStr);
	sb.append("当前线程数:   ").append(bean.getThreadCount()).append(spliteStr);
	sb.append("总启用线程数:   ").append(bean.	getTotalStartedThreadCount()).append(spliteStr);
	return sb.toString();
}
 
Example 10
Source File: ThreadDumper.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Nonnull
public static ThreadInfo[] getThreadInfos(@Nonnull ThreadMXBean threadMXBean, boolean sort) {
  ThreadInfo[] threads;
  try {
    threads = threadMXBean.dumpAllThreads(false, false);
  }
  catch (Exception ignored) {
    threads = threadMXBean.getThreadInfo(threadMXBean.getAllThreadIds(), Integer.MAX_VALUE);
  }
  if (sort) {
    sort(threads);
  }
  return threads;
}
 
Example 11
Source File: ThreadDumpCmd.java    From Doradus with Apache License 2.0 5 votes vote down vote up
@Override
public RESTResponse invoke() {
    StringBuilder dump = new StringBuilder();
    dump.append("Doradus Thread Dump @ ");
    dump.append(Utils.formatDate(System.currentTimeMillis()));
    dump.append("\n\n");
    
    ThreadMXBean threadBean = ManagementFactory.getThreadMXBean();
    ThreadInfo[] threadInfos = threadBean.dumpAllThreads(true, true);
    for (ThreadInfo thread : threadInfos) {
        dump.append(thread.toString());
    }
    return new RESTResponse(HttpCode.OK, dump.toString());
}
 
Example 12
Source File: JSR166TestCase.java    From streamsupport with GNU General Public License v2.0 5 votes vote down vote up
/**
 * A debugging tool to print stack traces of most threads, as jstack does.
 * Uninteresting threads are filtered out.
 */
static void dumpTestThreads() {
    SecurityManager sm = System.getSecurityManager();
    if (sm != null) {
        try {
            System.setSecurityManager(null);
        } catch (SecurityException giveUp) {
            return;
        }
    }

    ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean();
    System.err.println("------ stacktrace dump start ------");
    for (ThreadInfo info : threadMXBean.dumpAllThreads(true, true)) {
        final String name = info.getThreadName();
        String lockName;
        if ("Signal Dispatcher".equals(name))
            continue;
        if ("Reference Handler".equals(name)
            && (lockName = info.getLockName()) != null
            && lockName.startsWith("java.lang.ref.Reference$Lock"))
            continue;
        if ("Finalizer".equals(name)
            && (lockName = info.getLockName()) != null
            && lockName.startsWith("java.lang.ref.ReferenceQueue$Lock"))
            continue;
        if ("checkForWedgedTest".equals(name))
            continue;
        System.err.print(info);
    }
    System.err.println("------ stacktrace dump end ------");

    if (sm != null) System.setSecurityManager(sm);
}
 
Example 13
Source File: ThreadMain.java    From jdk-source-analysis with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) {
    ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean();
    ThreadInfo[] threadInfos = threadMXBean.dumpAllThreads(false, false);
    for (ThreadInfo info : threadInfos) {
        System.out.printf("[%d]%s\n", info.getThreadId(), info.getThreadName());
    }
}
 
Example 14
Source File: DeadlockDetector.java    From mapleLemon with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void run() {
    boolean noDeadLocks = true;

    while (noDeadLocks) {
        try {
            ThreadMXBean bean = ManagementFactory.getThreadMXBean();
            long[] threadIds = bean.findDeadlockedThreads();

            if (threadIds != null) {
                log.error("检测到死锁!!");
                this.sb = new StringBuilder();
                noDeadLocks = false;

                ThreadInfo[] infos = bean.getThreadInfo(threadIds);
                this.sb.append("\n线程锁信息: \n");
                for (ThreadInfo threadInfo : infos) {
                    printThreadInfo(threadInfo);
                    LockInfo[] lockInfos = threadInfo.getLockedSynchronizers();
                    MonitorInfo[] monitorInfos = threadInfo.getLockedMonitors();

                    printLockInfo(lockInfos);
                    printMonitorInfo(threadInfo, monitorInfos);
                }

                this.sb.append("\n线程转储: \n");
                for (ThreadInfo ti : bean.dumpAllThreads(true, true)) {
                    printThreadInfo(ti);
                }
                log.error(this.sb.toString());
            }
            Thread.sleep(this.checkInterval);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}
 
Example 15
Source File: JavaUtils.java    From incubator-ratis with Apache License 2.0 4 votes vote down vote up
static void dumpAllThreads(Consumer<String> println) {
  final ThreadMXBean threadMxBean = ManagementFactory.getThreadMXBean();
  for (ThreadInfo ti : threadMxBean.dumpAllThreads(true, true)) {
    println.accept(ti.toString());
  }
}
 
Example 16
Source File: SdcInfoContentGenerator.java    From datacollector with Apache License 2.0 4 votes vote down vote up
public void threadDump(BundleWriter writer) throws IOException {
  writer.markStartOfFile("runtime/threads.txt");

  ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean();
  ThreadInfo[] threads = threadMXBean.dumpAllThreads(true, true);

  // Sadly we can't easily do info.toString() as the implementation is hardcoded to cut the stack trace only to 8
  // items which does not serve our purpose well. Hence we have custom implementation that prints entire stack trace
  // for all threads.
  for(ThreadInfo info: threads) {
    StringBuilder sb = new StringBuilder("\"" + info.getThreadName() + "\"" + " Id=" + info.getThreadId() + " " + info.getThreadState());
    if (info.getLockName() != null) {
      sb.append(" on " + info.getLockName());
    }
    if (info.getLockOwnerName() != null) {
      sb.append(" owned by \"" + info.getLockOwnerName() + "\" Id=" + info.getLockOwnerId());
    }
    if (info.isSuspended()) {
      sb.append(" (suspended)");
    }
    if (info.isInNative()) {
      sb.append(" (in native)");
    }
    sb.append('\n');
    int i = 0;
    for(StackTraceElement ste : info.getStackTrace()) {
      if (i == 0 && info.getLockInfo() != null) {
        Thread.State ts = info.getThreadState();
        switch (ts) {
          case BLOCKED:
            sb.append("\t-  blocked on " + info.getLockInfo());
            sb.append('\n');
            break;
          case WAITING:
            sb.append("\t-  waiting on " + info.getLockInfo());
            sb.append('\n');
            break;
          case TIMED_WAITING:
            sb.append("\t-  waiting on " + info.getLockInfo());
            sb.append('\n');
            break;
          default:
        }
      }
      sb.append("\tat " + ste.toString());
      sb.append('\n');

      i++;

      for (MonitorInfo mi : info.getLockedMonitors()) {
        if (mi.getLockedStackDepth() == i) {
          sb.append("\t-  locked " + mi);
          sb.append('\n');
        }
      }
    }

    LockInfo[] locks = info.getLockedSynchronizers();
    if (locks.length > 0) {
      sb.append("\n\tNumber of locked synchronizers = " + locks.length);
      sb.append('\n');
      for (LockInfo li : locks) {
        sb.append("\t- " + li);
        sb.append('\n');
      }
    }
    sb.append('\n');

    writer.write(sb.toString());
  }

  writer.markEndOfFile();
}
 
Example 17
Source File: CF6Impl.java    From gemfirexd-oss with Apache License 2.0 4 votes vote down vote up
@Override
public ThreadInfo[] dumpAllThreads(ThreadMXBean bean, boolean lockedMonitors,
    boolean lockedSynchronizers) {
  return bean.dumpAllThreads(lockedMonitors, lockedSynchronizers);
}
 
Example 18
Source File: GfxdLocalLockService.java    From gemfirexd-oss with Apache License 2.0 4 votes vote down vote up
public static void generateThreadDump(StringBuilder msg) {
  ThreadMXBean mbean = ManagementFactory.getThreadMXBean();
  for (ThreadInfo tInfo : mbean.dumpAllThreads(true, true)) {
    msg.append('"').append(tInfo.getThreadName()).append('"').append(" Id=")
        .append(tInfo.getThreadId()).append(' ')
        .append(tInfo.getThreadState());
    if (tInfo.getLockName() != null) {
      msg.append(" on ").append(tInfo.getLockName());
    }
    if (tInfo.getLockOwnerName() != null) {
      msg.append(" owned by \"").append(tInfo.getLockOwnerName())
          .append("\" Id=").append(tInfo.getLockOwnerId());
    }
    if (tInfo.isSuspended()) {
      msg.append(" (suspended)");
    }
    if (tInfo.isInNative()) {
      msg.append(" (in native)");
    }
    msg.append(SanityManager.lineSeparator);
    final StackTraceElement[] stackTrace = tInfo.getStackTrace();
    for (int index = 0; index < stackTrace.length; ++index) {
      msg.append("\tat ").append(stackTrace[index].toString())
          .append(SanityManager.lineSeparator);
      if (index == 0 && tInfo.getLockInfo() != null) {
        final Thread.State ts = tInfo.getThreadState();
        switch (ts) {
          case BLOCKED:
            msg.append("\t-  blocked on ").append(tInfo.getLockInfo())
                .append(SanityManager.lineSeparator);
            break;
          case WAITING:
            msg.append("\t-  waiting on ").append(tInfo.getLockInfo())
                .append(SanityManager.lineSeparator);
            break;
          case TIMED_WAITING:
            msg.append("\t-  waiting on ").append(tInfo.getLockInfo())
                .append(SanityManager.lineSeparator);
            break;
          default:
        }
      }

      for (MonitorInfo mi : tInfo.getLockedMonitors()) {
        if (mi.getLockedStackDepth() == index) {
          msg.append("\t-  locked ").append(mi)
              .append(SanityManager.lineSeparator);
        }
      }
    }

    final LockInfo[] locks = tInfo.getLockedSynchronizers();
    if (locks.length > 0) {
      msg.append(SanityManager.lineSeparator)
          .append("\tNumber of locked synchronizers = ").append(locks.length)
          .append(SanityManager.lineSeparator);
      for (LockInfo li : locks) {
        msg.append("\t- ").append(li).append(SanityManager.lineSeparator);
      }
    }
    msg.append(SanityManager.lineSeparator);
  }
}
 
Example 19
Source File: JMServer.java    From jmonitor with GNU General Public License v2.0 4 votes vote down vote up
@HttpMapping(url = "/loadThreadInfo")
public JSONObject doLoadThreadInfo(Map<String, Object> param) {
    try {
        String app = ((HttpServletRequest) param.get(JMDispatcher.REQ)).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);
    }
}
 
Example 20
Source File: MonitorProvider.java    From parallec with Apache License 2.0 2 votes vote down vote up
/**
 * Gets the thread dump.
 *
 * @return the thread dump
 */
public ThreadInfo[] getThreadDump() {
    ThreadMXBean threadMxBean = ManagementFactory.getThreadMXBean();
    return threadMxBean.dumpAllThreads(true, true);
}