List of usage examples for java.lang.management ManagementFactory getThreadMXBean
public static ThreadMXBean getThreadMXBean()
From source file:com.streamsets.datacollector.restapi.AdminResource.java
@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)// ww w .j a va 2s. c o m @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(); }
From source file:org.opendaylight.controller.config.threadpool.fixed.FixedThreadPoolConfigBeanTest.java
private int countThreadsByPrefix(String prefix) { ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean(); int result = 0; List<String> names = new ArrayList<>(); for (ThreadInfo threadInfo : threadMXBean.dumpAllThreads(false, false)) { names.add(threadInfo.getThreadName()); if (threadInfo.getThreadName().startsWith(prefix)) { result++;//from w ww.j av a 2 s.com } } LOG.info("Current threads {}", names); return result; }
From source file:com.streamsets.datacollector.bundles.content.SdcInfoContentGenerator.java
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()); }/* w ww.j av a 2 s .c om*/ 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(); }
From source file:org.apache.hadoop.metrics.jvm.JvmMetrics.java
private void doThreadUpdates() { ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean(); long threadIds[] = threadMXBean.getAllThreadIds(); ThreadInfo[] threadInfos = threadMXBean.getThreadInfo(threadIds, 0); int threadsNew = 0; int threadsRunnable = 0; int threadsBlocked = 0; int threadsWaiting = 0; int threadsTimedWaiting = 0; int threadsTerminated = 0; for (ThreadInfo threadInfo : threadInfos) { // threadInfo is null if the thread is not alive or doesn't exist if (threadInfo == null) continue; Thread.State state = threadInfo.getThreadState(); if (state == NEW) { threadsNew++;/*from www . j a va 2 s. c om*/ } else if (state == RUNNABLE) { threadsRunnable++; } else if (state == BLOCKED) { threadsBlocked++; } else if (state == WAITING) { threadsWaiting++; } else if (state == TIMED_WAITING) { threadsTimedWaiting++; } else if (state == TERMINATED) { threadsTerminated++; } } metrics.setMetric("threadsNew", threadsNew); metrics.setMetric("threadsRunnable", threadsRunnable); metrics.setMetric("threadsBlocked", threadsBlocked); metrics.setMetric("threadsWaiting", threadsWaiting); metrics.setMetric("threadsTimedWaiting", threadsTimedWaiting); metrics.setMetric("threadsTerminated", threadsTerminated); }
From source file:Main.java
/** * Get a list of all threads. Since there is always at least one thread, * this method never returns null or an empty array. * /*from w w w . j a v a2s .co m*/ * @return an array of threads */ public static Thread[] getAllThreads() { final ThreadGroup root = getRootThreadGroup(); final ThreadMXBean thbean = ManagementFactory.getThreadMXBean(); int nAlloc = thbean.getThreadCount(); int n = 0; Thread[] threads = null; do { nAlloc *= 2; threads = new Thread[nAlloc]; n = root.enumerate(threads, true); } while (n == nAlloc); return java.util.Arrays.copyOf(threads, n); }
From source file:com.opengamma.web.WebAbout.java
/** * Gets the thread JMX. * @return the thread JMX */ public ThreadMXBean getThreadJmx() { return ManagementFactory.getThreadMXBean(); }
From source file:com.alibaba.druid.benckmark.pool.Case2.java
private void p0(final DataSource dataSource, String name, int threadCount) throws Exception { final CountDownLatch startLatch = new CountDownLatch(1); final CountDownLatch endLatch = new CountDownLatch(threadCount); final AtomicLong blockedStat = new AtomicLong(); final AtomicLong waitedStat = new AtomicLong(); for (int i = 0; i < threadCount; ++i) { Thread thread = new Thread() { public void run() { try { startLatch.await();/*from w w w. j a v a2s . c om*/ long threadId = Thread.currentThread().getId(); long startBlockedCount, startWaitedCount; { ThreadInfo threadInfo = ManagementFactory.getThreadMXBean().getThreadInfo(threadId); startBlockedCount = threadInfo.getBlockedCount(); startWaitedCount = threadInfo.getWaitedCount(); } for (int i = 0; i < LOOP_COUNT; ++i) { Connection conn = dataSource.getConnection(); conn.close(); } ThreadInfo threadInfo = ManagementFactory.getThreadMXBean().getThreadInfo(threadId); long blockedCount = threadInfo.getBlockedCount() - startBlockedCount; long waitedCount = threadInfo.getWaitedCount() - startWaitedCount; blockedStat.addAndGet(blockedCount); waitedStat.addAndGet(waitedCount); } catch (Exception ex) { ex.printStackTrace(); } endLatch.countDown(); } }; thread.start(); } long startMillis = System.currentTimeMillis(); long startYGC = TestUtil.getYoungGC(); long startFullGC = TestUtil.getFullGC(); startLatch.countDown(); endLatch.await(); long millis = System.currentTimeMillis() - startMillis; long ygc = TestUtil.getYoungGC() - startYGC; long fullGC = TestUtil.getFullGC() - startFullGC; System.out.println("thread " + threadCount + " " + name + " millis : " + NumberFormat.getInstance().format(millis) + ", YGC " + ygc + " FGC " + fullGC + " blockedCount " + blockedStat.get() + " waitedCount " + waitedStat.get()); }
From source file:com.janrain.backplane.server.metrics.MetricsAccumulator.java
private Map<String, Object> outputJVMUsage() { long mb = 1048576; Map<String, Object> out = new LinkedHashMap<String, Object>(); long startTime = ManagementFactory.getRuntimeMXBean().getStartTime(); int totalLiveThreads = ManagementFactory.getThreadMXBean().getThreadCount(); double loadAverage = ManagementFactory.getOperatingSystemMXBean().getSystemLoadAverage(); MemoryUsage mu = ManagementFactory.getMemoryMXBean().getHeapMemoryUsage(); String startTimeString = BackplaneConfig.ISO8601.format(new Date(startTime)); out.put("type", "jvm"); out.put("unit", "mb"); out.put("heap_used", mu.getUsed() / mb); out.put("heap_free", (mu.getMax() - mu.getUsed()) / mb); out.put("heap_max", mu.getMax() / mb); out.put("jvm_start_time", startTimeString); out.put("total_live_threads", totalLiveThreads); out.put("load_average_minute", String.format("%2.2f", loadAverage)); return out;/* w w w. ja v a 2 s . c o m*/ }
From source file:org.apache.asterix.test.runtime.LangExecutionUtil.java
private static void checkOpenRunFileLeaks() throws IOException { if (SystemUtils.IS_OS_WINDOWS) { return;//from www . ja va 2 s. c om } // Only run the check on Linux and MacOS. RuntimeMXBean runtimeMXBean = ManagementFactory.getRuntimeMXBean(); String processName = runtimeMXBean.getName(); String processId = processName.split("@")[0]; // Checks whether there are leaked run files from operators. Process process = Runtime.getRuntime() .exec(new String[] { "bash", "-c", "lsof -p " + processId + "|grep waf|wc -l" }); try (BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()))) { int runFileCount = Integer.parseInt(reader.readLine().trim()); if (runFileCount != 0) { System.out.print(takeDumpJSON(ManagementFactory.getThreadMXBean())); outputLeakedOpenFiles(processId); throw new AssertionError("There are " + runFileCount + " leaked run files."); } } }
From source file:org.apache.hadoop.util.TestShell.java
private static int countTimerThreads() { ThreadMXBean threadBean = ManagementFactory.getThreadMXBean(); int count = 0; ThreadInfo[] infos = threadBean.getThreadInfo(threadBean.getAllThreadIds(), 20); for (ThreadInfo info : infos) { if (info == null) continue; for (StackTraceElement elem : info.getStackTrace()) { if (elem.getClassName().contains("Timer")) { count++;// www.j ava 2 s .c o m break; } } } return count; }