@Override public void run() { while (goOn) { try { long[] ids = ManagementFactory.getThreadMXBean().findDeadlockedThreads(); checkCount.incrementAndGet(); ids = ids == null ? new long[0] : ids; if (ids.length > 0) { deadlocked.addAll(asList(ids)); } if (ids.length == 1) { throw new RuntimeException("Found 1 deadlocked thread: " + ids[0]); } else if (ids.length > 0) { ThreadInfo[] infos = ManagementFactory.getThreadMXBean().getThreadInfo(ids, Integer.MAX_VALUE); System.err.println("Found " + ids.length + " deadlocked threads: "); for (ThreadInfo inf : infos) { System.err.println(inf.toString()); } throw new RuntimeException("Found " + ids.length + " deadlocked threads"); } Thread.sleep(100); } catch (InterruptedException | RuntimeException x) { fail(x); } } }
@Override public int run(String[] args) throws Exception { Job job = new Job(conf); job.setJarByClass(StatisticsGenerator.class); job.setInputFormatClass(SequenceFileInputFormat.class); job.setOutputFormatClass(SequenceFileOutputFormat.class); SequenceFileInputFormat.addInputPath(job, new Path(args[0])); SequenceFileOutputFormat.setOutputPath(job, new Path(args[1])); job.setMapperClass(StatisticsMap.class); job.setReducerClass(StatisticsReduce.class); job.setMapOutputKeyClass(SortedMapWritableComparable.class); job.setMapOutputValueClass(BytesWritable.class); job.setNumReduceTasks(16); job.setOutputKeyClass(Text.class); job.setOutputValueClass(BytesWritable.class); long startTime = ManagementFactory.getThreadMXBean().getThreadCpuTime(Thread.currentThread().getId()); boolean success = job.waitForCompletion(true); long endTime = ManagementFactory.getThreadMXBean().getThreadCpuTime(Thread.currentThread().getId()); double duration = (endTime - startTime) / Math.pow(10, 9); logger.info( "=== Job Finished in " + duration + " seconds " + (success ? "(success)" : "(failure)")); return success ? 0 : 1; }
@RequiresNonNull("startupLogger") private static void start( File baseDir, Map<String, String> properties, @Nullable Instrumentation instrumentation, @Nullable File glowrootJarFile) throws Exception { ManagementFactory.getThreadMXBean().setThreadCpuTimeEnabled(true); ManagementFactory.getThreadMXBean().setThreadContentionMonitoringEnabled(true); String version = Version.getVersion(MainEntryPoint.class); String collectorHost = properties.get("glowroot.collector.host"); if (Strings.isNullOrEmpty(collectorHost)) { collectorHost = System.getProperty("glowroot.collector.host"); } Collector customCollector = loadCustomCollector(baseDir); if (Strings.isNullOrEmpty(collectorHost) && customCollector == null) { glowrootAgentInit = new GlowrootFatAgentInit(); } else { if (customCollector != null) { startupLogger.info("Using collector: {}", customCollector.getClass().getName()); } glowrootAgentInit = new GlowrootThinAgentInit(); } glowrootAgentInit.init( baseDir, collectorHost, customCollector, properties, instrumentation, glowrootJarFile, version, false); startupLogger.info("Glowroot started (version {})", version); }
public MemoryMonitor() { LOG.info("initializing"); this.springContextId = "Unknown"; ManagementFactory.getThreadMXBean().setThreadContentionMonitoringEnabled(true); ManagementFactory.getThreadMXBean().setThreadCpuTimeEnabled(true); lowMemoryListener = new NotificationListener() { public void handleNotification(Notification n, Object hb) { if (n.getType().equals(MemoryNotificationInfo.MEMORY_THRESHOLD_EXCEEDED)) { Map<String, String> memoryUsageStatistics = new HashMap<String, String>(); memoryUsageStatistics.put( "MemoryMXBean: " + MemoryType.HEAP, ManagementFactory.getMemoryMXBean().getHeapMemoryUsage().toString()); memoryUsageStatistics.put( "MemoryMXBean:" + MemoryType.NON_HEAP, ManagementFactory.getMemoryMXBean().getNonHeapMemoryUsage().toString()); for (MemoryPoolMXBean pool : ManagementFactory.getMemoryPoolMXBeans()) { memoryUsageStatistics.put( "MemoryPoolMXBean: " + pool.getType(), pool.getUsage().toString()); } for (Listener listener : listeners) { listener.memoryUsageLow( springContextId, memoryUsageStatistics, Arrays.toString( ManagementFactory.getThreadMXBean().findMonitorDeadlockedThreads())); } } } }; ((NotificationEmitter) ManagementFactory.getMemoryMXBean()) .addNotificationListener(lowMemoryListener, null, null); }
/** Uses reflection to get ThreadInfo with monitors & synchronizers. */ private static ThreadInfo[] getThreadInfo(long[] ids) { try { Method m = ThreadMXBean.class.getDeclaredMethod( "getThreadInfo", new Class[] {long[].class, boolean.class, boolean.class}); Object o = m.invoke(ManagementFactory.getThreadMXBean(), new Object[] {ids, true, true}); return (ThreadInfo[]) o; } catch (Throwable t) { } // fallback to retrieving info w/o monitor & synchronizer info return ManagementFactory.getThreadMXBean().getThreadInfo(ids, Integer.MAX_VALUE); }
private void createRuntimeProps(MemberStateImpl memberState) { Runtime runtime = Runtime.getRuntime(); ThreadMXBean threadMxBean = ManagementFactory.getThreadMXBean(); RuntimeMXBean runtimeMxBean = ManagementFactory.getRuntimeMXBean(); ClassLoadingMXBean clMxBean = ManagementFactory.getClassLoadingMXBean(); MemoryMXBean memoryMxBean = ManagementFactory.getMemoryMXBean(); MemoryUsage heapMemory = memoryMxBean.getHeapMemoryUsage(); MemoryUsage nonHeapMemory = memoryMxBean.getNonHeapMemoryUsage(); Map<String, Long> map = new HashMap<String, Long>(); map.put( "runtime.availableProcessors", Integer.valueOf(runtime.availableProcessors()).longValue()); map.put("date.startTime", runtimeMxBean.getStartTime()); map.put("seconds.upTime", runtimeMxBean.getUptime()); map.put("memory.maxMemory", runtime.maxMemory()); map.put("memory.freeMemory", runtime.freeMemory()); map.put("memory.totalMemory", runtime.totalMemory()); map.put("memory.heapMemoryMax", heapMemory.getMax()); map.put("memory.heapMemoryUsed", heapMemory.getUsed()); map.put("memory.nonHeapMemoryMax", nonHeapMemory.getMax()); map.put("memory.nonHeapMemoryUsed", nonHeapMemory.getUsed()); map.put("runtime.totalLoadedClassCount", clMxBean.getTotalLoadedClassCount()); map.put( "runtime.loadedClassCount", Integer.valueOf(clMxBean.getLoadedClassCount()).longValue()); map.put("runtime.unloadedClassCount", clMxBean.getUnloadedClassCount()); map.put("runtime.totalStartedThreadCount", threadMxBean.getTotalStartedThreadCount()); map.put("runtime.threadCount", Integer.valueOf(threadMxBean.getThreadCount()).longValue()); map.put( "runtime.peakThreadCount", Integer.valueOf(threadMxBean.getPeakThreadCount()).longValue()); map.put( "runtime.daemonThreadCount", Integer.valueOf(threadMxBean.getDaemonThreadCount()).longValue()); memberState.setRuntimeProps(map); }
public class TimeTracker extends LinkedHashMap<String, Interval> { private static final long serialVersionUID = 4253748581102583813L; private final int nanosecondsPerMillisecond = 1000000; private ThreadMXBean bean = ManagementFactory.getThreadMXBean(); protected long getTimeInMilliseconds() { if (bean.isCurrentThreadCpuTimeSupported()) return bean.getCurrentThreadCpuTime() / nanosecondsPerMillisecond; else return System.nanoTime() / nanosecondsPerMillisecond; } public void start(final String name) { put(name, new Interval(getTimeInMilliseconds())); } public void end(final String name) { get(name).setEnd(getTimeInMilliseconds()); } public void outputTable(int width, PrintStream out) { // Heading for (final Entry<String, Interval> e : entrySet()) out.print(Strings.padStart(e.getKey(), width, ' ') + " "); out.println(); // Values for (final Entry<String, Interval> e : entrySet()) out.print(Strings.padStart(e.getValue().toString(), width, ' ') + " "); out.println(); } }
public static void main(String args[]) { // get top-level thread group ThreadGroup top = Thread.currentThread().getThreadGroup(); ThreadGroup parent; do { parent = top.getParent(); if (parent != null) top = parent; } while (parent != null); // get the thread count int activeCount = top.activeCount(); Map<Thread, StackTraceElement[]> stackTraces = Thread.getAllStackTraces(); ThreadMXBean threadBean = ManagementFactory.getThreadMXBean(); int threadCount = threadBean.getThreadCount(); long[] threadIds = threadBean.getAllThreadIds(); System.out.println("ThreadGroup: " + activeCount + " active thread(s)"); System.out.println("Thread: " + stackTraces.size() + " stack trace(s) returned"); System.out.println("ThreadMXBean: " + threadCount + " live threads(s)"); System.out.println("ThreadMXBean: " + threadIds.length + " thread Id(s)"); // check results are consistent boolean failed = false; if (activeCount != stackTraces.size()) failed = true; if (activeCount != threadCount) failed = true; if (activeCount != threadIds.length) failed = true; if (failed) { throw new RuntimeException("inconsistent results"); } }
public void init(final ServletContext context, final Map<String, String> paras) { _startTime = new Date(); _context = context; _sipFactory = (SipFactory) context.getAttribute(ServletContextConstants.SIP_FACTORY); _mrcpFactory = (MrcpFactory) context.getAttribute(ServletContextConstants.MRCP_FACTORY); _appJarUrl = _context.getRealPath("/") + "WEB-INF" + File.separator + "lib" + File.separator + "tropo.jar"; _cache = Collections.synchronizedMap(new WeakHashMap<Object, Application>()); _tmx = ManagementFactory.getThreadMXBean(); _mmx = ManagementFactory.getMemoryMXBean(); try { _tropoBuildDate = Utils.getManifestAttribute(_appJarUrl, "Build-Date"); } catch (final IOException t) { LOG.error(t.toString(), t); _tropoBuildDate = "Unknown"; } try { _tropoVersionNo = Utils.getManifestAttribute(_appJarUrl, "Version-No"); } catch (final IOException t) { LOG.error(t.toString(), t); _tropoVersionNo = "Unknown"; } try { _tropoBuildNo = Utils.getManifestAttribute(_appJarUrl, "Build-No"); } catch (final IOException t) { LOG.error(t.toString(), t); _tropoBuildNo = "Unknown"; } LOG.info(toString() + " / " + getVersionNo() + " / " + getBuildNo()); }
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++; } 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); }
/// The watcher thread - from the Runnable interface. // This has to be pretty anal to avoid monitor lockup, lost // threads, etc. public synchronized void run() { Thread me = Thread.currentThread(); me.setPriority(Thread.MAX_PRIORITY); ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean(); startTimeInNs = threadMXBean.getCurrentThreadCpuTime(); if (enabled.get()) { do { loop.set(false); try { wait(millis); } catch (InterruptedException e) { } } while (enabled.get() && loop.get()); } if (enabled.get() && targetThread.isAlive()) { isDoneRunning.set(true); printThread(); if (kill) { logger.warn( "Trying to kill thread with id:" + targetThread.getId() + " but did not as it can cause deadlocks etc."); // targetThread.interrupt(); // targetThread.stop(); //Never kill thread - it can cause other problems } done(); isDoneRunning.set(false); } }
@Override public void execute(OperationContext context, ModelNode operation) throws OperationFailedException { validator.validate(operation); ThreadMXBean mbean = ManagementFactory.getThreadMXBean(); try { long id = operation.require(PlatformMBeanConstants.ID).asLong(); ThreadInfo info = null; if (operation.hasDefined(PlatformMBeanConstants.MAX_DEPTH)) { info = mbean.getThreadInfo(id, operation.require(PlatformMBeanConstants.MAX_DEPTH).asInt()); } else { info = mbean.getThreadInfo(id); } final ModelNode result = context.getResult(); if (info != null) { result.set(PlatformMBeanUtil.getDetypedThreadInfo(info, mbean.isThreadCpuTimeSupported())); } } catch (SecurityException e) { throw new OperationFailedException(new ModelNode().set(e.toString())); } context.completeStep(); }
public CPUClock() { threadMXBean = ManagementFactory.getThreadMXBean(); if (!threadMXBean.isCurrentThreadCpuTimeSupported()) { throw new IllegalStateException("Information about thread CPU times not supported"); } }
/** * Returns object of class ‘"proc_time"’ which is a numeric vector of length 5, containing the * user, system, and total elapsed times for the currently running R process, and the cumulative * sum of user and system times of any child processes spawned by it on which it has waited. * * <p>_The ‘user time’ is the CPU time charged for the execution of user instructions of the * calling process. The ‘system time’ is the CPU time charged for execution by the system on * behalf of the calling process._ */ @Builtin("proc.time") public static DoubleVector procTime() { DoubleArrayVector.Builder result = new DoubleArrayVector.Builder(); StringVector.Builder names = new StringVector.Builder(); long totalCPUTime; long userCPUTime; long elapsedTime; // There doesn't seem to be any platform-independent way of accessing // CPU use for the whole JVM process, so we'll have to make do // with the timings for the thread we're running on. // // Additionally, the MX Beans may not be available in all environments, // so we need to fallback to app try { ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean(); totalCPUTime = threadMXBean.getCurrentThreadCpuTime(); userCPUTime = threadMXBean.getCurrentThreadUserTime(); RuntimeMXBean runtimeMXBean = ManagementFactory.getRuntimeMXBean(); elapsedTime = runtimeMXBean.getUptime(); } catch (Error e) { // ThreadMXBean is not available in all environments // Specifically, AppEngine will throw variously SecurityErrors or // ClassNotFoundErrors if we try to access these classes userCPUTime = totalCPUTime = java.lang.System.nanoTime(); elapsedTime = new Date().getTime(); } // user.self names.add("user.self"); result.add(userCPUTime / NANOSECONDS_PER_SECOND); // sys.self names.add("sys.self"); result.add((totalCPUTime - userCPUTime) / NANOSECONDS_PER_SECOND); // elapsed // (wall clock time) names.add("elapsed"); result.add(elapsedTime); // AFAIK, we don't have any platform independent way of accessing // this info. // user.child names.add("user.child"); result.add(0); // sys.child names.add("sys.child"); result.add(0); result.setAttribute(Symbols.NAMES, names.build()); result.setAttribute(Symbols.CLASS, StringVector.valueOf("proc_time")); return result.build(); }
public class Clock { public interface IClock { void start(); void stop(); long getDelta(); } public static ThreadMXBean threadMX = ManagementFactory.getThreadMXBean(); // public static boolean canThreadCPU = threadMX.isCurrentThreadCpuTimeSupported(); public static boolean canThreadCPU = false; public class ClockMX implements IClock { public long startTime = 0; public long timeDelta = 0; @Override public void start() { this.startTime = threadMX.getCurrentThreadCpuTime(); } @Override public void stop() { this.timeDelta = threadMX.getCurrentThreadCpuTime() - this.startTime; } @Override public long getDelta() { return this.timeDelta; } } public class ClockNano implements IClock { public long startTime = 0; public long timeDelta = 0; @Override public void start() { this.startTime = System.nanoTime(); } @Override public void stop() { this.timeDelta = System.nanoTime() - this.startTime; } @Override public long getDelta() { return this.timeDelta; } } public static IClock getNewClock() { if (Clock.canThreadCPU) return new Clock().new ClockMX(); else return new Clock().new ClockNano(); } }
@IgnoreJRERequirement public static ThreadInfo[] getThreadInfos() { ThreadMXBean mbean = ManagementFactory.getThreadMXBean(); return mbean.getThreadInfo( mbean.getAllThreadIds(), mbean.isObjectMonitorUsageSupported(), mbean.isSynchronizerUsageSupported()); }
@Override public void verify(QueryContext context, String queryString) { if (!context.getSession().isAdmin()) throw new QueryParseException("95050", -1, -1, null); ThreadMXBean bean = ManagementFactory.getThreadMXBean(); if (!bean.isThreadCpuTimeSupported()) throw new QueryParseException("95051", -1, -1, null); if (!bean.isThreadCpuTimeEnabled()) throw new QueryParseException("95051", -1, -1, null); }
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()); } }
private static void runExecutionBoundedTest(int nthreads, List<Counter> counters, int nexecutions) throws InterruptedException { final List<CounterThread> threads = new ArrayList<CounterThread>(); for (int i = 0; i < nthreads; i++) { CounterThread t; t = new CounterThread(counters.get(i % counters.size()), nexecutions); t.start(); threads.add(t); } CounterThread.shoot(); // let all the threads go crazy at the same time for (int i = 0; i < nthreads; i++) { CounterThread t = threads.get(i); t.join(30000); if (t.isAlive()) { System.out.println("stuck thread name: " + t.toString()); System.out.println("stuck thread state: " + t.getState()); safe.ReentrantLock l = (safe.ReentrantLock) t.getLock(); System.out.println("thread waiting lock: " + l); System.out.println("stuck thread increments: " + t.getExecutions()); System.out.println("stuck thread counter value: " + t.getCounterCount()); Thread other = l.getOwner(); System.out.println("lock owner: " + other); if (other != null) { System.out.println("owner name: " + other.toString()); System.out.println("state owner: " + other.getState()); } // Keep program alive to dump thread stacks with: jstack -l $(pidof java) System.out.println( java.lang.management.ManagementFactory.getThreadMXBean().getPeakThreadCount()); while (true) {} } } long sum = 0; for (int i = 0; i < counters.size(); ++i) { sum += counters.get(i).getCount(); } System.out.println(sum); System.out.println( java.lang.management.ManagementFactory.getThreadMXBean().getPeakThreadCount()); }
public void testComparison() throws Exception { ThreadMXBean bean = (ThreadMXBean) ManagementFactory.getThreadMXBean(); Random random = new SecureRandom(); Long[] keys = new Long[ITERATIONS]; String[] values = new String[ITERATIONS]; for (int i = 0; i < keys.length; i++) { keys[i] = random.nextLong(); values[i] = "value-" + random.nextLong(); } long id = Thread.currentThread().getId(); for (int n = 0; n < 10; n++) { ArrayPositionCache<String> cache = new ArrayPositionCache<String>(100); LeastRecentlyUsedMap<Long, String> map = new LeastRecentlyUsedMap<Long, String>(100); System.gc(); Thread.sleep(100); long memoryStart1 = bean.getThreadAllocatedBytes(id); long start1 = System.currentTimeMillis(); for (int i = 0; i < values.length; i++) { cache.cache(keys[i], values[i]); } long finish1 = System.currentTimeMillis(); long memoryFinish1 = bean.getThreadAllocatedBytes(id); System.gc(); Thread.sleep(100); long memoryStart2 = bean.getThreadAllocatedBytes(id); long start2 = System.currentTimeMillis(); for (int i = 0; i < values.length; i++) { map.put(keys[i], values[i]); } long finish2 = System.currentTimeMillis(); long memoryFinish2 = bean.getThreadAllocatedBytes(id); System.err.println( "PositionCache time=" + (finish1 - start1) + " memory=" + (memoryFinish1 - memoryStart1)); System.err.println( "LeastRecentlyUsedMap time=" + (finish2 - start2) + " memory=" + (memoryFinish2 - memoryStart2)); Set<Long> currentKeys = map.keySet(); // reconcile the keys for (Long currentKey : currentKeys) { assertNotNull(map.get(currentKey)); assertNotNull(cache.fetch(currentKey)); assertEquals(cache.fetch(currentKey), map.get(currentKey)); } } }
public void testResolutionUser() { ThreadMXBean threadBean = ManagementFactory.getThreadMXBean(); int count = 0; long startTime = threadBean.getCurrentThreadUserTime(); long stopTime = threadBean.getCurrentThreadUserTime(); while (stopTime == startTime) { stopTime = threadBean.getCurrentThreadUserTime(); count++; } System.out.println( "Resolution via UserTime: " + (stopTime - startTime) + "ns in " + count + " iterations."); }
public static String threadDump() { StringBuilder threadDump = new StringBuilder(); ThreadMXBean threadMx = ManagementFactory.getThreadMXBean(); if (threadMx.isObjectMonitorUsageSupported() && threadMx.isSynchronizerUsageSupported()) { // Print lock info if, and only if, both object monitor usage and synchronizer usage are // supported. dumpThreadInfo(threadDump, true, threadMx); } else { dumpThreadInfo(threadDump, false, threadMx); } return threadDump.toString(); }
@Override public void query(QueryContext context, String queryString, MetadataCallback callback) { ThreadMXBean bean = ManagementFactory.getThreadMXBean(); ArrayList<ThreadCpuUsage> usages = new ArrayList<ThreadCpuUsage>(); for (long tid : bean.getAllThreadIds()) { long time = bean.getThreadCpuTime(tid); usages.add(new ThreadCpuUsage(tid, time)); } try { Thread.sleep(1000); } catch (InterruptedException e) { } Map<Thread, StackTraceElement[]> stacks = Thread.getAllStackTraces(); for (long tid : bean.getAllThreadIds()) { ThreadCpuUsage usage = find(usages, tid); if (usage != null) usage.secondTime = bean.getThreadCpuTime(tid); } Collections.sort(usages); for (ThreadCpuUsage usage : usages) { long elapsed = usage.secondTime - usage.firstTime; // remove just created thread or sleeping threads (noisy) if (elapsed <= 0) continue; StringBuilder sb = new StringBuilder(); Thread t = findThread(stacks, usage.tid); if (t == null) continue; StackTraceElement[] stack = findStack(stacks, usage.tid); for (StackTraceElement el : stack) { sb.append( String.format( "%s.%s %s\n", el.getClassName(), el.getMethodName(), getFileAndLineNumber(el))); } Map<String, Object> m = new HashMap<String, Object>(); m.put("tid", t.getId()); m.put("name", t.getName()); m.put("state", t.getState().toString()); m.put("priority", t.getPriority()); m.put("usage", elapsed); m.put("stacktrace", sb.toString()); callback.onPush(new Row(m)); } }
public static Thread[] getAllThreads() { final ThreadGroup root = getRootThreadGroup(); final ThreadMXBean thbean = ManagementFactory.getThreadMXBean(); int nAlloc = thbean.getThreadCount(); int n = 0; Thread[] threads; do { nAlloc *= 2; threads = new Thread[nAlloc]; n = root.enumerate(threads, true); } while (n == nAlloc); return threads; }
/** Constructor */ public ThreadMeasurement() { threadsInfo = null; ThreadMXBean threadBean = ManagementFactory.getThreadMXBean(); threadIds = threadBean.getAllThreadIds(); threadsInfo = threadBean.getThreadInfo(threadIds, THREAD_TRACE_DEPTH); threadCount = threadIds.length; threadNames = new String[threadCount]; for (int i = 0; i < threadCount; i++) { if (threadsInfo[i] != null) threadNames[i] = threadsInfo[i].getThreadName(); } } // Constructor end
public DataBuffer getServerStatus(int version) { DataBuffer buffer = new DataBuffer(); // system info double cpu = roundToDecimals(cpuMonitor.getCpuUsage() * 100, 2); long freeMem = Runtime.getRuntime().freeMemory(); long maxMem = Runtime.getRuntime().maxMemory(); long totalMem = Runtime.getRuntime().totalMemory(); buffer.writeDouble(cpu); buffer.writeLong(freeMem); buffer.writeLong(maxMem); buffer.writeLong(totalMem); // threads list long totalThreadsCpuTime = 0; long[] threadIds = ManagementFactory.getThreadMXBean().getAllThreadIds(); buffer.writeInt(threadIds.length); // 多少条线程. for (int i = 0; i < threadIds.length; i++) { long id = threadIds[i]; String name = ManagementFactory.getThreadMXBean().getThreadInfo(id).getThreadName(); long cpuTime = 0; if (ManagementFactory.getThreadMXBean().isThreadCpuTimeSupported() && ManagementFactory.getThreadMXBean().isThreadCpuTimeEnabled()) { cpuTime = ManagementFactory.getThreadMXBean().getThreadCpuTime(id); totalThreadsCpuTime += cpuTime; } buffer.writeLong(id); buffer.writeString(name); buffer.writeLong(cpuTime); } buffer.writeLong(totalThreadsCpuTime); return buffer; }
public void testTakeCPUTime() { ThreadMXBean mbean = ManagementFactory.getThreadMXBean(); if (!mbean.isThreadCpuTimeEnabled()) { fail("ThreadMXBean CPU time reporting is not enabled"); } long msecMultiplier = 1000 * 1000; long msecGoal = 10; long cpuGoal = msecGoal * msecMultiplier; long beforeCPU = mbean.getCurrentThreadCpuTime(); MyMetricFunctions.takeCPUTime(cpuGoal); long afterCPU = mbean.getCurrentThreadCpuTime(); assertTrue((afterCPU - beforeCPU) > cpuGoal); }
/** Count the number of threads that have a stack frame containing the given string */ private static int countThreads(String search) { 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(search)) { count++; break; } } } return count; }
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(); }
/** * A total hack to see if there are any active Java3D threads running * * @return any java3d threads running */ private static boolean anyJava3dThreadsActive() { ThreadMXBean threadBean = ManagementFactory.getThreadMXBean(); long[] ids = threadBean.getAllThreadIds(); for (int i = 0; i < ids.length; i++) { ThreadInfo info = threadBean.getThreadInfo(ids[i], Integer.MAX_VALUE); if (info == null) { continue; } if (info.getThreadState() != Thread.State.RUNNABLE) { continue; } if (info.getThreadName().indexOf("J3D") >= 0) { return true; } } return false; }