Java Code Examples for java.lang.management.ManagementFactory#getThreadMXBean()
The following examples show how to use
java.lang.management.ManagementFactory#getThreadMXBean() .
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: ConnectionManagerForTests.java From reladomo with Apache License 2.0 | 6 votes |
private String getRequestingClass() { long curThread = Thread.currentThread().getId(); ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean(); ThreadInfo threadInfo = threadMXBean.getThreadInfo(curThread, Integer.MAX_VALUE); StackTraceElement[] stackTrace = threadInfo.getStackTrace(); for (int i = 0; i < stackTrace.length; i++) { String className = stackTrace[i].getClassName(); if (className.endsWith("DatabaseObjectAbstract")) { String requestingClass = className.substring(0, className.length() - "DatabaseObjectAbstract".length()); return requestingClass; } } return null; }
Example 2
Source File: ConnectorStopDeadlockTest.java From TencentKona-8 with GNU General Public License v2.0 | 6 votes |
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(); } }
Example 3
Source File: ChromeTraceBuildListener.java From buck with Apache License 2.0 | 6 votes |
public ChromeTraceBuildListener( ProjectFilesystem projectFilesystem, InvocationInfo invocationInfo, Clock clock, ChromeTraceBuckConfig config, TaskManagerCommandScope managerScope, Optional<RemoteExecutionStatsProvider> reStatsProvider, CriticalPathEventListener criticalPathEventListener) throws IOException { this( projectFilesystem, invocationInfo, clock, Locale.US, TimeZone.getDefault(), ManagementFactory.getThreadMXBean(), config, managerScope, reStatsProvider, criticalPathEventListener); }
Example 4
Source File: SharedSynchronizer.java From openjdk-8 with GNU General Public License v2.0 | 6 votes |
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"); } }
Example 5
Source File: GetInternalThreads.java From jdk8u-dev-jdk with GNU General Public License v2.0 | 6 votes |
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); } }
Example 6
Source File: OSProcess.java From gemfirexd-oss with Apache License 2.0 | 6 votes |
/** dumps this vm's stacks and returns gzipped result */ public static byte[] zipStacks() throws IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream(10000); GZIPOutputStream zipOut = new GZIPOutputStream(baos, 10000); PrintWriter pw = new PrintWriter(zipOut, true); final GemFireCacheImpl.StaticSystemCallbacks sysCb = GemFireCacheImpl .getInternalProductCallbacks(); if (sysCb == null) { ThreadMXBean bean = ManagementFactory.getThreadMXBean(); long[] threadIds = bean.getAllThreadIds(); ThreadInfo[] infos = bean.getThreadInfo(threadIds, true, true); long thisThread = Thread.currentThread().getId(); for (int i = 0; i < infos.length; i++) { if (i != thisThread && infos[i] != null) { formatThreadInfo(infos[i], pw); } } } else { sysCb.printStacks(pw); } pw.flush(); zipOut.close(); byte[] result = baos.toByteArray(); return result; }
Example 7
Source File: TestUtils.java From osmo with GNU Lesser General Public License v2.1 | 6 votes |
/** * Provides information on all the threads in the current JVM. Useful for debugging. * * @return Formatted string with thread names, states and 5 element stack traces. */ public static String getThreadInfo() { ThreadMXBean tb = ManagementFactory.getThreadMXBean(); long[] ids = tb.getAllThreadIds(); ThreadInfo[] infos = tb.getThreadInfo(ids, 5); StringBuilder builder = new StringBuilder("Information for available threads:" + ln); for (ThreadInfo info : infos) { builder.append("Thread").append(ln); builder.append("-name=").append(info.getThreadName()).append(ln); builder.append("-state=").append(info.getThreadState()).append(ln); builder.append("-stacktrace (5 elements):").append(ln); StackTraceElement[] trace = info.getStackTrace(); for (StackTraceElement line : trace) { builder.append("--").append(line).append(ln); } } return builder.toString(); }
Example 8
Source File: ThreadLists.java From jdk8u-jdk with GNU General Public License v2.0 | 5 votes |
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"); } }
Example 9
Source File: ThreadMXBeanTool.java From dragonwell8_jdk with GNU General Public License v2.0 | 5 votes |
/** * Waits until {@link Thread} is in the certain {@link Thread.State} * and blocking on {@code object}. * * @param state The thread state * @param object The object to block on */ public static void waitUntilBlockingOnObject(Thread thread, Thread.State state, Object object) throws InterruptedException { String want = object == null ? null : object.getClass().getName() + '@' + Integer.toHexString(System.identityHashCode(object)); ThreadMXBean tmx = ManagementFactory.getThreadMXBean(); while (thread.isAlive()) { ThreadInfo ti = tmx.getThreadInfo(thread.getId()); if (ti.getThreadState() == state && (want == null || want.equals(ti.getLockName()))) { return; } Thread.sleep(1); } }
Example 10
Source File: OdaTiming.java From OpenDA with GNU Lesser General Public License v3.0 | 5 votes |
/** Get CPU time in nanoseconds. */ private long getCpuTime( ) { ThreadMXBean bean; 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; }
Example 11
Source File: DeadLockDetector.java From aion-germany with GNU General Public License v3.0 | 5 votes |
/** * Create new DeadLockDetector with given values. * * @param sleepTime * @param doWhenDL */ public DeadLockDetector(int sleepTime, byte doWhenDL) { super("DeadLockDetector"); this.sleepTime = sleepTime * 1000; this.tmx = ManagementFactory.getThreadMXBean(); this.doWhenDL = doWhenDL; }
Example 12
Source File: StackTraceCommand.java From LagMonitor with MIT License | 5 votes |
@Override public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { if (!canExecute(sender, command)) { return true; } if (args.length > 0) { String threadName = args[0]; Map<Thread, StackTraceElement[]> allStackTraces = Thread.getAllStackTraces(); for (Map.Entry<Thread, StackTraceElement[]> entry : allStackTraces.entrySet()) { Thread thread = entry.getKey(); if (thread.getName().equalsIgnoreCase(threadName)) { StackTraceElement[] stackTrace = entry.getValue(); printStackTrace(sender, stackTrace); return true; } } sendError(sender, "No thread with that name found"); } else { ThreadMXBean threadBean = ManagementFactory.getThreadMXBean(); ThreadInfo threadInfo = threadBean.getThreadInfo(Thread.currentThread().getId(), MAX_DEPTH); printStackTrace(sender, threadInfo.getStackTrace()); } return true; }
Example 13
Source File: ThreadDumpCmd.java From Doradus with Apache License 2.0 | 5 votes |
@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 14
Source File: AnnotationTypeDeadlockTest.java From openjdk-8 with GNU General Public License v2.0 | 5 votes |
public static void main(String[] args) throws Exception { CountDownLatch prepareLatch = new CountDownLatch(2); AtomicInteger goLatch = new AtomicInteger(1); Task taskA = new Task(prepareLatch, goLatch, AnnA.class); Task taskB = new Task(prepareLatch, goLatch, AnnB.class); taskA.start(); taskB.start(); // wait until both threads start-up prepareLatch.await(); // let them go goLatch.set(0); // obtain ThreadMXBean ThreadMXBean threadBean = ManagementFactory.getThreadMXBean(); // wait for threads to finish or dead-lock while (taskA.isAlive() || taskB.isAlive()) { // attempt to join threads taskA.join(500L); taskB.join(500L); // detect dead-lock long[] deadlockedIds = threadBean.findMonitorDeadlockedThreads(); if (deadlockedIds != null && deadlockedIds.length > 0) { StringBuilder sb = new StringBuilder("deadlock detected:\n\n"); for (ThreadInfo ti : threadBean.getThreadInfo(deadlockedIds, Integer.MAX_VALUE)) { sb.append(ti); } throw new IllegalStateException(sb.toString()); } } }
Example 15
Source File: InvalidThreadID.java From jdk8u-dev-jdk with GNU General Public License v2.0 | 5 votes |
public static void main(String argv[]) { ThreadMXBean mbean = ManagementFactory.getThreadMXBean(); int cnt = 0; long [] idArr = {0, -1, -2, (Long.MIN_VALUE + 1), Long.MIN_VALUE}; if (mbean.isThreadCpuTimeSupported()) { for (int i = 0; i < idArr.length; i++) { try { mbean.getThreadCpuTime(idArr[i]); System.out.println("Test failed. IllegalArgumentException" + " expected for ID = " + idArr[i]); } catch (IllegalArgumentException iae) { cnt++; } } if (cnt != idArr.length) { throw new RuntimeException("Unexpected number of " + "IllegalArgumentException = " + cnt + " expected = " + idArr.length); } // CPU time for a non-existence thread long time = mbean.getThreadCpuTime(999999); if (time < 0 && time != -1) { throw new RuntimeException("Cpu time for thread 999999" + " is invalid = " + time + " expected to be -1."); } } System.out.println("Test passed."); }
Example 16
Source File: ThreadDumpActor.java From sunbird-lms-service with MIT License | 4 votes |
private void takeThreadDump() { final StringBuilder dump = new StringBuilder(); final StringBuilder details = new StringBuilder(); final StringBuilder info = new StringBuilder(); final ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean(); final ThreadInfo[] threadInfos = threadMXBean.getThreadInfo(threadMXBean.getAllThreadIds(), 100); details.append("Thread id | Thread name | CPU time | User time | Blocked time\n\n"); for (ThreadInfo threadInfo : threadInfos) { dump.append('"'); dump.append(threadInfo.getThreadName()); dump.append("\" "); final Thread.State state = threadInfo.getThreadState(); dump.append("\n java.lang.Thread.State: "); dump.append(state); final StackTraceElement[] stackTraceElements = threadInfo.getStackTrace(); for (final StackTraceElement stackTraceElement : stackTraceElements) { dump.append("\n at "); dump.append(stackTraceElement); } dump.append("\n\n"); long cputime = threadMXBean.getThreadCpuTime(threadInfo.getThreadId()); long usertime = threadMXBean.getThreadUserTime(threadInfo.getThreadId()); long blockedtime = threadInfo.getBlockedTime(); details.append( threadInfo.getThreadId() + " | " + threadInfo.getThreadName() + " | " + cputime + " | " + usertime + " | " + blockedtime + "\n\n"); info.append(threadInfo.toString() + "\n\n"); } System.out.println("=== thread-dump start ==="); System.out.println(dump.toString()); System.out.println("=== thread-dump end ===\n\n"); System.out.println("=== thread-cpu start ==="); System.out.println(details.toString()); System.out.println("=== thread-cpu end ===\n\n"); System.out.println("=== thread-info start ==="); System.out.println(info.toString()); System.out.println("=== thread-info end ===\n\n"); }
Example 17
Source File: Timers.java From visualvm with GNU General Public License v2.0 | 4 votes |
/** Should be called at earliest possible time */ public static void initialize() { ManagementFactory.getThreadMXBean(); getThreadCPUTimeInNanos(); initializeProcessCPUTime(); }
Example 18
Source File: JvmUtils.java From flink with Apache License 2.0 | 4 votes |
/** * Creates a thread dump of the current JVM. * * @return the thread dump of current JVM */ public static Collection<ThreadInfo> createThreadDump() { ThreadMXBean threadMxBean = ManagementFactory.getThreadMXBean(); return Arrays.asList(threadMxBean.dumpAllThreads(true, true)); }
Example 19
Source File: TestThreadAllocationEvent.java From dragonwell8_jdk with GNU General Public License v2.0 | 4 votes |
private long getThreadAllocatedBytes() { ThreadMXBean bean = (ThreadMXBean) ManagementFactory.getThreadMXBean(); return bean.getThreadAllocatedBytes(Thread.currentThread().getId()); }
Example 20
Source File: JvmMetrics.java From big-c with Apache License 2.0 | 4 votes |
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); }