@Override protected void render(Block html) { set(TITLE, join("Angel ExecutorsBlock")); TBODY<TABLE<Hamlet>> tbody = html.h1("ExecutorsBlock").table("#jobs").thead().tr().th(_TH, "id").th(_TH, "name") .th(_TH, "state").th(_TH, "stacktrace")._()._().tbody(); ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean(); ThreadInfo[] threadInfo = threadMXBean.dumpAllThreads(true, true); StringBuilder stackTraceString; for (ThreadInfo t : threadInfo) { stackTraceString = new StringBuilder(); StackTraceElement[] stackTrace = t.getStackTrace(); for (StackTraceElement s : stackTrace) { stackTraceString.append(s.toString()).append("\n"); } tbody.tr().td(String.valueOf(t.getThreadId())).td(String.valueOf(t.getThreadName())) .td(String.valueOf(t.getThreadState())).td(String.valueOf(stackTraceString.toString()))._(); } tbody._()._(); }
/** * Gets thread stack. * * @return the thread stack */ private String getThreadStack() { ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean(); ThreadInfo[] threadInfo = threadMXBean.dumpAllThreads(true, true); StringBuilder stackTraceString= new StringBuilder("ParameterServer\n"); StringBuilder infoBlock= new StringBuilder("\n"); for(ThreadInfo t : threadInfo) { infoBlock = new StringBuilder("\n\n"); infoBlock.append("threadid: ").append(t.getThreadId()).append(" threadname: ").append(t.getThreadName()).append(" threadstate: ").append(t.getThreadState()).append("\n"); for(StackTraceElement stackTraceElement : t.getStackTrace()) { infoBlock.append(" ").append(stackTraceElement.toString()).append("\n"); } stackTraceString.append(infoBlock).append("\n\n"); } return stackTraceString.toString(); }
@Override public String call() { Map<String, String> memoryMap = new HashMap<>(); OperatingSystemMXBean osMxBean = ManagementFactory.getOperatingSystemMXBean(); double cpu = osMxBean.getSystemLoadAverage(); memoryMap.put("cpuLoad", String.format(doubleStringFormatter, round(cpu, doubleRoundPlaces))); ThreadMXBean threadmxBean = ManagementFactory.getThreadMXBean(); int threadCount = threadmxBean.getThreadCount(); memoryMap.put("cpuRunningThreads", String.valueOf(threadCount)); MemoryMXBean memBean = ManagementFactory.getMemoryMXBean(); MemoryUsage memHeapUsage = memBean.getHeapMemoryUsage(); MemoryUsage nonHeapUsage = memBean.getNonHeapMemoryUsage(); memoryMap.put("heapInit", String.valueOf(memHeapUsage.getInit())); memoryMap.put("heapMax", String.valueOf(memHeapUsage.getMax())); memoryMap.put("heapCommit", String.valueOf(memHeapUsage.getCommitted())); memoryMap.put("heapUsed", String.valueOf(memHeapUsage.getUsed())); memoryMap.put("nonHeapInit", String.valueOf(nonHeapUsage.getInit())); memoryMap.put("nonHeapMax", String.valueOf(nonHeapUsage.getMax())); memoryMap.put("nonHeapCommit", String.valueOf(nonHeapUsage.getCommitted())); memoryMap.put("nonHeapUsed", String.valueOf(nonHeapUsage.getUsed())); return memoryMap.toString(); }
@Override public void sense(final MetricRecorder.Context metricContext) { ThreadMXBean mxBean = ManagementFactory.getThreadMXBean(); int current = mxBean.getThreadCount(); int peak = mxBean.getPeakThreadCount(); if (peak > historicalPeak) { historicalPeak = peak; } metricContext.record(THREADS, current, Unit.NONE); metricContext.record(PERIODIC_PEAK_THREADS, peak, Unit.NONE); metricContext.record(PEAK_THREADS, historicalPeak, Unit.NONE); mxBean.resetPeakThreadCount(); }
@Test public void testReset() { System.out.println("reset"); ThreadMXBean tbean = ManagementFactory.getThreadMXBean(); addStacktrace(tbean.getThreadInfo(tbean.getAllThreadIds(), Integer.MAX_VALUE), System.nanoTime()); addStacktrace(tbean.getThreadInfo(tbean.getAllThreadIds(), Integer.MAX_VALUE), System.nanoTime()); instance.reset(); assertTrue(instance.methodInfos.size()-1 == 0); assertTrue(instance.threadIds.size() == 0); assertTrue(instance.threadNames.size() == 0); assertEquals(-1L, instance.currentDumpTimeStamp); //assertEquals(-1L, instance.firstDumpTimeStamp); assertEquals(0, instance.stackTraceCount); try { instance.createSnapshot(System.currentTimeMillis()); fail(); } catch (CPUResultsSnapshot.NoDataAvailableException ex) { } }
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++; break; } } } return count; }
static String buildDeadlockInfo() { ThreadMXBean threadBean = ManagementFactory.getThreadMXBean(); long[] threadIds = threadBean.findMonitorDeadlockedThreads(); if (threadIds != null && threadIds.length > 0) { StringWriter stringWriter = new StringWriter(); PrintWriter out = new PrintWriter(stringWriter); ThreadInfo[] infos = threadBean.getThreadInfo(threadIds, true, true); for (ThreadInfo ti : infos) { printThreadInfo(ti, out); printLockInfo(ti.getLockedSynchronizers(), out); out.println(); } out.close(); return stringWriter.toString(); } else { return null; } }
/** * Count the number of threads that have a stack frame containing * the given string */ protected 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; }
public static List<TInfo> getAllThreadInfo(){ List<TInfo> threads = new ArrayList<>(); ThreadMXBean threadBean = ManagementFactory.getThreadMXBean(); long[] ids = threadBean.getAllThreadIds(); ThreadInfo[] infos = threadBean.getThreadInfo(ids); for (ThreadInfo info : infos){ long id = info.getThreadId(); TInfo tInfo = new TInfo(); tInfo.name = info.getThreadName(); tInfo.id = id; tInfo.state = info.getThreadState(); tInfo.cpuTime = threadBean.getThreadCpuTime(id); threads.add(tInfo); } Collections.sort(threads,new Comparator<TInfo>() { @Override public int compare(TInfo o1, TInfo o2) { return Long.compare(o2.cpuTime,o1.cpuTime); } }); return threads; }
public static ThreadInfo[] dump(int maxDepth,boolean onlyDeadLock){ ThreadMXBean threadBean = ManagementFactory.getThreadMXBean(); long[] ids ; if(onlyDeadLock) { ids = threadBean.findDeadlockedThreads(); }else { ids = threadBean.getAllThreadIds(); } if(ids !=null) { return threadBean.getThreadInfo(ids, maxDepth); } else { return null; } }
public static void start() { if (started) throw new IllegalStateException("Already Started."); OperatingSystemMXBean os = ManagementFactory.getOperatingSystemMXBean(); ThreadMXBean thread = ManagementFactory.getThreadMXBean(); Runtime r = Runtime.getRuntime(); int mb = 0x100000; lastSystemTime = System.nanoTime(); lastProcessCpuTime = calculateProcessCpuTime(os); Async.task("AsyncInfoMonitorThread", () -> { threadCount = thread.getThreadCount(); availableProcessors = r.availableProcessors(); freeMemory = Runtime.getRuntime().freeMemory() / mb; maxMemory = Runtime.getRuntime().maxMemory() / mb; totalMemory = Runtime.getRuntime().totalMemory() / mb; cpuUsage = calculateCpuUsage(os); vpsCPUUsage = getVpsCPUUsage(os); vpsFreeMemory = calculateVPSFreeMemory(os); vpsMaxMemory = calculateVPSMaxMemory(os); vpsUsedMemory = vpsMaxMemory - vpsFreeMemory; }, 1); started = true; }
@Override public void bindTo(MeterRegistry registry) { ThreadMXBean threadBean = ManagementFactory.getThreadMXBean(); Gauge.builder("jvm.threads.peak", threadBean, ThreadMXBean::getPeakThreadCount) .tags(tags) .description("The peak live thread count since the Java virtual machine started or peak was reset") .register(registry); Gauge.builder("jvm.threads.daemon", threadBean, ThreadMXBean::getDaemonThreadCount) .tags(tags) .description("The current number of live daemon threads") .register(registry); Gauge.builder("jvm.threads.live", threadBean, ThreadMXBean::getThreadCount) .tags(tags) .description("The current number of live threads including both daemon and non-daemon threads") .register(registry); }
/** * @return Set of the IDs of all threads that are started except the "main" thread. */ public Set<Long> getAllThreadIDsExceptMain() { ThreadMXBean thbean = ManagementFactory.getThreadMXBean(); // get the IDs of all live threads. long[] threadIDs = thbean.getAllThreadIds(); Set<Long> res = new HashSet<Long>(); // get the IDs of all threads except main for (long id : threadIDs) { Thread t = getThread(id); if (t != null && !"main".equals(t.getName())) { res.add(id); } } return res; }
/** * @return a list of all threads started in the JVM. */ public List<Thread> getAllThreads() { final ThreadGroup root = getRootThreadGroup(); final ThreadMXBean thbean = ManagementFactory.getThreadMXBean(); // get the number of all live threads int nAlloc = thbean.getThreadCount(); int n = 0; Thread[] threads; do { nAlloc *= 2; // increase the size since more threads may have been created threads = new Thread[nAlloc]; n = root.enumerate(threads, true); // get all active threads from this thread group } while (n == nAlloc); // stop if all active threads are enumerated List<Thread> res = new ArrayList<Thread>(); for (Thread th : threads) { res.add(th); } return res; }
@Override public Object next() { if (!beforeFirst) { throw new IllegalStateException(); } beforeFirst = false; final ThreadsInfo threadsInfo = new ThreadsInfo(); final DrillbitEndpoint endpoint = context.getIdentity(); threadsInfo.hostname = endpoint.getAddress(); threadsInfo.user_port = endpoint.getUserPort(); final ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean(); threadsInfo.total_threads = threadMXBean.getPeakThreadCount(); threadsInfo.busy_threads = threadMXBean.getThreadCount(); return threadsInfo; }
/** * Constructs a ThreadMonitor object to get thread information * in a remote JVM. */ public ThreadMonitor(MBeanServerConnection server) throws IOException { this.server = server; this.tmbean = newPlatformMXBeanProxy(server, THREAD_MXBEAN_NAME, ThreadMXBean.class); try { objname = new ObjectName(THREAD_MXBEAN_NAME); } catch (MalformedObjectNameException e) { // should not reach here InternalError ie = new InternalError(e.getMessage()); ie.initCause(e); throw ie; } parseMBeanInfo(); }
/** * Getter for the "JvmThreadInstCpuTimeNs" variable. */ public Long getJvmThreadInstCpuTimeNs() throws SnmpStatusException { long l = 0; final ThreadMXBean tmb = JvmThreadingImpl.getThreadMXBean(); try { if (tmb.isThreadCpuTimeSupported()) { l = tmb.getThreadCpuTime(info.getThreadId()); log.debug("getJvmThreadInstCpuTimeNs", "Cpu time ns : " + l); //Cpu time measurement is disabled or the id is not valid. if(l == -1) l = 0; } } catch (UnsatisfiedLinkError e) { // XXX Revisit: catch TO BE EVENTUALLY REMOVED log.debug("getJvmThreadInstCpuTimeNs", "Operation not supported: " + e); } return new Long(l); }
/** * Getter for the "JvmThreadContentionMonitoring" variable. */ public EnumJvmThreadContentionMonitoring getJvmThreadContentionMonitoring() throws SnmpStatusException { ThreadMXBean mbean = getThreadMXBean(); if(!mbean.isThreadContentionMonitoringSupported()) { log.debug("getJvmThreadContentionMonitoring", "Unsupported ThreadContentionMonitoring"); return JvmThreadContentionMonitoringUnsupported; } if(mbean.isThreadContentionMonitoringEnabled()) { log.debug("getJvmThreadContentionMonitoring", "Enabled ThreadContentionMonitoring"); return JvmThreadContentionMonitoringEnabled; } else { log.debug("getJvmThreadContentionMonitoring", "Disabled ThreadContentionMonitoring"); return JvmThreadContentionMonitoringDisabled; } }
/** * 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; }
public static void main(String[] args) throws Exception { MyThread t = new MyThread(); t.setDaemon(true); t.start(); ThreadMXBean tmbean = ManagementFactory.getThreadMXBean(); if (!tmbean.isSynchronizerUsageSupported()) { System.out.println("Monitoring of synchronizer usage not supported") ; return; } long[] result = tmbean.findDeadlockedThreads(); if (result != null) { throw new RuntimeException("TEST FAILED: result should be null"); } }
public static void main(String[] args) throws Exception { long value = mbean.getInternalThreadCount(); if (value < MIN_VALUE_FOR_PASS || value > MAX_VALUE_FOR_PASS) { throw new RuntimeException("Internal thread count " + "illegal value: " + value + " " + "(MIN = " + MIN_VALUE_FOR_PASS + "; " + "MAX = " + MAX_VALUE_FOR_PASS + ")"); } System.out.println("Internal Thread Count = " + value); ThreadMXBean thread = ManagementFactory.getThreadMXBean(); if (!thread.isThreadCpuTimeSupported()) { System.out.println("Thread Cpu Time is not supported."); return; } while(!testCPUTime()) { Thread.sleep(100); } }
/** * Waits until {@link TestThread} is in the certain {@link State} * and blocking on {@code object}. * * @param state The thread state * @param object The object to block on */ public void waitUntilBlockingOnObject(Thread.State state, Object object) { String want = object == null ? null : object.getClass().getName() + '@' + Integer.toHexString(System.identityHashCode(object)); ThreadMXBean tmx = ManagementFactory.getThreadMXBean(); while (isAlive()) { ThreadInfo ti = tmx.getThreadInfo(getId()); if (ti.getThreadState() == state && (want == null || want.equals(ti.getLockName()))) { return; } try { Thread.sleep(1); } catch (InterruptedException e) { } } }
@Override public String envi() { Map<String, String> result = new HashMap<String, String>(); // 系统信息 result.put(RegistryMonitorConstants.OSNAME, System.getProperty(RegistryMonitorConstants.OSNAME, "not specified")); result.put(RegistryMonitorConstants.JAVA_VERSION, System.getProperty(RegistryMonitorConstants.JAVA_VERSION, "not specified")); result.put(RegistryMonitorConstants.JDK_PATH, System.getProperty(RegistryMonitorConstants.JDK_PATH, "not specified")); result.put(RegistryMonitorConstants.APP_PATH, System.getProperty(RegistryMonitorConstants.APP_PATH, "not specified")); // jvm信息 MemoryMXBean memorymbean = ManagementFactory.getMemoryMXBean(); MemoryUsage usage = memorymbean.getHeapMemoryUsage(); result.put(RegistryMonitorConstants.JVM_INIT, String.valueOf(usage.getInit())); result.put(RegistryMonitorConstants.JVM_MAX, String.valueOf(usage.getMax())); result.put(RegistryMonitorConstants.JVM_USED, String.valueOf(usage.getUsed())); //线程信息 ThreadMXBean tm = (ThreadMXBean) ManagementFactory.getThreadMXBean(); result.put(RegistryMonitorConstants.JVM_THREAD_COUNT, String.valueOf(tm.getThreadCount())); result.put(RegistryMonitorConstants.JVM_PEAKTHREAD_COUNT, String.valueOf(tm.getPeakThreadCount())); result.put(RegistryMonitorConstants.JVM_CURRENTTHREAD_CPUTIME, String.valueOf(tm.getCurrentThreadCpuTime())); result.put(RegistryMonitorConstants.JVM_CURRENTTHREAD_USERTIME, String.valueOf(tm.getCurrentThreadUserTime())); return JSON.toJSONString(result); }
public static boolean isMonitorLockHeldByThread(Object o, Thread t) { int oihc = System.identityHashCode(o); ThreadMXBean tmxbean = ManagementFactory.getThreadMXBean(); ThreadInfo[] tinfos = tmxbean.dumpAllThreads(true, false); for (ThreadInfo ti : tinfos) { if (!(t != null && t.getId() != ti.getThreadId())) { for (MonitorInfo mi : ti.getLockedMonitors()) { if (mi.getIdentityHashCode() == oihc) { return true; } } } } return false; }
/** * 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 ------"); }
/** * 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; if ("process reaper".equals(name)) continue; if (name != null && name.startsWith("ForkJoinPool.commonPool-worker")) continue; System.err.print(info); } System.err.println("------ stacktrace dump end ------"); }
static void waitForBlock(Thread t) { Thread currentThread = Thread.currentThread(); System.out.println("waiting for thread " + t.getName() + " to block " + "on a lock held by thread " + currentThread.getName()); ThreadMXBean tm = ManagementFactory.getThreadMXBean(); while (true) { ThreadInfo ti = tm.getThreadInfo(t.getId()); if (ti == null) { System.out.println(" thread has exited"); return; } if (ti.getLockOwnerId() == currentThread.getId()) { System.out.println(" thread now blocked"); return; } Thread.yield(); } }
private String getThreadStack() { ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean(); ThreadInfo[] threadInfo = threadMXBean.dumpAllThreads(true, true); StringBuilder stackTraceString = new StringBuilder("Worker\n"); StringBuilder infoBlock = new StringBuilder("\n"); for (ThreadInfo t : threadInfo) { infoBlock = new StringBuilder("\n\n"); infoBlock.append("threadid: ").append(t.getThreadId()).append(" threadname: ").append(t.getThreadName()).append(" threadstate: ").append(t.getThreadState()).append("\n"); for (StackTraceElement stackTraceElement : t.getStackTrace()) { infoBlock.append(" ").append(stackTraceElement.toString()).append("\n"); } stackTraceString.append(infoBlock).append("\n\n"); } return stackTraceString.toString(); }
/** * Determine if there are any threads whose name matches the regex. * @param pattern a Pattern object used to match thread names * @return true if there is any thread that matches the pattern */ public static boolean anyThreadMatching(Pattern pattern) { ThreadMXBean threadBean = ManagementFactory.getThreadMXBean(); ThreadInfo[] infos = threadBean.getThreadInfo(threadBean.getAllThreadIds(), 20); for (ThreadInfo info : infos) { if (info == null) continue; if (pattern.matcher(info.getThreadName()).matches()) { return true; } } return false; }
public static Map<String,Number> getThreadStats(){ Map<String,Number> rtn = new HashMap<>(); ThreadMXBean threadBean = ManagementFactory.getThreadMXBean(); rtn.put("currentThreadCount",threadBean.getThreadCount()); rtn.put("daemonThreadCount", threadBean.getDaemonThreadCount()); rtn.put("totalStartedThreadCount", threadBean.getTotalStartedThreadCount()); rtn.put("peakThreadCount", threadBean.getPeakThreadCount()); return rtn; }
/** Get CPU time in nanoseconds. */ private long getCpuTime( ) { ThreadMXBean bean = null; try { bean = ManagementFactory.getThreadMXBean( ); } catch (Error e) { // not supported (happens in the by means of IKVM converted version (.net) return 0L; } return bean.isCurrentThreadCpuTimeSupported( ) ? bean.getCurrentThreadCpuTime( ) : 0L; }
@Test public void thePathOfFifteenThousandJumps() { byte[] bytecode = new byte[15000 * 6 + 3]; int k = 0; while (k < 15000 * 6) { int target = k + 6; bytecode[k++] = 0x5b; // JUMPDEST bytecode[k++] = 0x62; // PUSH3 bytecode[k++] = (byte)(target >> 16); bytecode[k++] = (byte)(target >> 8); bytecode[k++] = (byte)(target & 0xff); bytecode[k++] = 0x56; // JUMP } bytecode[k++] = 0x5b; // JUMPDEST bytecode[k++] = 0x60; // PUSH1 bytecode[k++] = 0x01; // 1 ThreadMXBean thread = ManagementFactory.getThreadMXBean(); Runtime runtime = Runtime.getRuntime(); runtime.gc(); long initialMemory = runtime.totalMemory() - runtime.freeMemory(); long initialTime = thread.getCurrentThreadCpuTime(); testCode(bytecode, 15000 * 3 + 2, "0000000000000000000000000000000000000000000000000000000000000001"); long finalTime = thread.getCurrentThreadCpuTime(); long finalMemory = runtime.totalMemory() - runtime.freeMemory(); System.out.println(String.format("Execution Time %s nanoseconds", finalTime - initialTime)); System.out.println(String.format("Delta memory %s", finalMemory - initialMemory)); }
/** * Waits until {@link Thread} is in native. */ public static void waitUntilInNative(Thread thread) throws InterruptedException { ThreadMXBean tmx = ManagementFactory.getThreadMXBean(); while (thread.isAlive()) { ThreadInfo ti = tmx.getThreadInfo(thread.getId()); if (ti.isInNative()) { return; } Thread.sleep(1); } }