Java Code Examples for java.lang.management.ThreadMXBean#getThreadInfo()
The following examples show how to use
java.lang.management.ThreadMXBean#getThreadInfo() .
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: TestThread.java From jdk8u60 with GNU General Public License v2.0 | 6 votes |
/** * 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) { } } }
Example 2
Source File: ThreadingManager.java From vi with Apache License 2.0 | 6 votes |
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; }
Example 3
Source File: ConnectorStopDeadlockTest.java From jdk8u-jdk 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 4
Source File: DeadLockDetector.java From cst with GNU Lesser General Public License v3.0 | 6 votes |
@Override public void run() { do { ThreadMXBean tmx = ManagementFactory.getThreadMXBean(); long[] ids = tmx.findDeadlockedThreads(); if (ids != null) { ThreadInfo[] infos = tmx.getThreadInfo(ids, true, true); System.out.println("The following threads are deadlocked: "); for (ThreadInfo ti : infos) { System.out.println(ti); } } try { Thread.currentThread().sleep(this.ddRefreshPeriod); } catch (InterruptedException e) { e.printStackTrace(); } } while (shouldLoop); }
Example 5
Source File: ThreadDeadlockDumpProvider.java From TNT4J with Apache License 2.0 | 6 votes |
@Override public DumpCollection getDump() { Dump dump = new Dump("JavaDeadlockedThreads", this); ThreadMXBean tmbean = ManagementFactory.getThreadMXBean(); long[] dead = tmbean.findMonitorDeadlockedThreads(); dump.add("java.thread.deadlock.count", dead == null ? 0 : dead.length); if (dead != null) { ThreadInfo[] tinfos = tmbean.getThreadInfo(dead, Integer.MAX_VALUE); for (ThreadInfo ti : tinfos) { dump.add(ti.getThreadName() + "-" + ti.getThreadId(), ti); } } return dump; }
Example 6
Source File: ConnectorStopDeadlockTest.java From jdk8u60 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 7
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 8
Source File: ZooKeeperHighAvailabilityITCase.java From flink with Apache License 2.0 | 6 votes |
private static String generateThreadDump() { final StringBuilder dump = new StringBuilder(); final ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean(); final ThreadInfo[] threadInfos = threadMXBean.getThreadInfo(threadMXBean.getAllThreadIds(), 100); for (ThreadInfo threadInfo : threadInfos) { dump.append('"'); dump.append(threadInfo.getThreadName()); dump.append('"'); final Thread.State state = threadInfo.getThreadState(); dump.append(System.lineSeparator()); dump.append(" java.lang.Thread.State: "); dump.append(state); final StackTraceElement[] stackTraceElements = threadInfo.getStackTrace(); for (final StackTraceElement stackTraceElement : stackTraceElements) { dump.append(System.lineSeparator()); dump.append(" at "); dump.append(stackTraceElement); } dump.append(System.lineSeparator()); dump.append(System.lineSeparator()); } return dump.toString(); }
Example 9
Source File: JMServer.java From jmonitor with GNU General Public License v2.0 | 6 votes |
@HttpMapping(url = "/deadlockCheck") public JSONObject doDeadlockCheck(Map<String, Object> param) { try { String app = ((HttpServletRequest) param.get(JMDispatcher.REQ)).getParameter("app"); ThreadMXBean tBean = JMConnManager.getThreadMBean(app); JSONObject json = new JSONObject(); long[] dTh = tBean.findDeadlockedThreads(); if (dTh != null) { ThreadInfo[] threadInfo = tBean.getThreadInfo(dTh, Integer.MAX_VALUE); StringBuffer sb = new StringBuffer(); for (ThreadInfo info : threadInfo) { sb.append("\n").append(info); } json.put("hasdeadlock", true); json.put("info", sb); return json; } json.put("hasdeadlock", false); return json; } catch (IOException e) { throw new RuntimeException(e); } }
Example 10
Source File: ShellIsActiveWithThreadSTacksOnFailure.java From bonita-studio with GNU General Public License v2.0 | 6 votes |
public String getFailureMessage() { final StringBuilder dump = new StringBuilder(); final ThreadMXBean threadMxBean = ManagementFactory.getThreadMXBean(); final ThreadInfo[] threadInfos = threadMxBean.getThreadInfo(threadMxBean.getAllThreadIds(), 100); for (final ThreadInfo threadInfo : threadInfos) { dump.append('"'); dump.append(threadInfo.getThreadName()); dump.append('"'); dump.append("\n java.lang.Thread.State:"); dump.append(threadInfo.getThreadState()); for (final StackTraceElement stactraceElement : threadInfo.getStackTrace()) { dump.append("\n at "); dump.append(stactraceElement); } dump.append("\n\n"); } dump.append("\nAvailablable shells:\n"); for (final SWTBotShell shell : bot.shells()) { dump.append(shell.getText()).append("\n"); } return "The shell '" + text + "' did not activate.\n" //$NON-NLS-1$ //$NON-NLS-2$ + dump.toString(); }
Example 11
Source File: ThreadMXBeanThreadInfosHandler.java From wildfly-core with GNU Lesser General Public License v2.1 | 5 votes |
@Override public void execute(OperationContext context, ModelNode operation) throws OperationFailedException { try { final long[] ids = getIds(operation); ThreadMXBean mbean = ManagementFactory.getThreadMXBean(); ThreadInfo[] infos; if (operation.hasDefined(PlatformMBeanConstants.LOCKED_MONITORS)) { lockedValidator.validate(operation); infos = mbean.getThreadInfo(ids, operation.require(PlatformMBeanConstants.LOCKED_MONITORS).asBoolean(), operation.require(PlatformMBeanConstants.LOCKED_SYNCHRONIZERS).asBoolean()); } else if (operation.hasDefined(PlatformMBeanConstants.MAX_DEPTH)) { depthValidator.validate(operation); infos = mbean.getThreadInfo(ids, operation.require(PlatformMBeanConstants.MAX_DEPTH).asInt()); } else { infos = mbean.getThreadInfo(ids); } final ModelNode result = context.getResult(); if (infos != null) { result.setEmptyList(); for (ThreadInfo info : infos) { if (info != null) { result.add(PlatformMBeanUtil.getDetypedThreadInfo(info, mbean.isThreadCpuTimeSupported())); } else { // Add an undefined placeholder result.add(); } } } } catch (SecurityException e) { throw new OperationFailedException(e.toString()); } }
Example 12
Source File: GfxdMemberMBeanBridge.java From gemfirexd-oss with Apache License 2.0 | 5 votes |
public String detectDeadlocksAlt() { ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean(); long[] findDeadlockedThreads = threadMXBean.findDeadlockedThreads(); StringBuilder builder = new StringBuilder(); if (findDeadlockedThreads == null || findDeadlockedThreads.length == 0) { builder.append("No deadlocks detected."); } else { ThreadInfo[] threadsInfo = threadMXBean.getThreadInfo(findDeadlockedThreads); for (ThreadInfo threadInfo : threadsInfo) { builder.append(threadInfo.toString()).append(ManagementUtils.LINE_SEPARATOR); } } return builder.toString(); }
Example 13
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 14
Source File: AnnotationTypeDeadlockTest.java From native-obfuscator with GNU General Public License v3.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: LogicalIOProcessorRuntimeTask.java From tez with Apache License 2.0 | 5 votes |
/** * Print all threads in JVM (only for debugging) */ void printThreads() { //Print the status of all threads in JVM ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean(); long[] threadIds = threadMXBean.getAllThreadIds(); for (Long id : threadIds) { ThreadInfo threadInfo = threadMXBean.getThreadInfo(id); // The thread could have been shutdown before we read info about it. if (threadInfo != null) { if (LOG.isDebugEnabled()) { LOG.debug("ThreadId : " + id + ", name=" + threadInfo.getThreadName()); } } } }
Example 16
Source File: AnnotationTypeDeadlockTest.java From jdk8u-dev-jdk 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 17
Source File: ThreadDumpTest.java From bistoury with GNU General Public License v3.0 | 5 votes |
/** * 主方法 */ public static void main(String[] args) throws Exception { ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean(); long[] ids = threadMXBean.getAllThreadIds(); ThreadInfo[] threadInfo = threadMXBean.getThreadInfo(ids); for (ThreadInfo info : threadInfo) { System.out.println(info.getThreadId() + "\t" + info.getThreadState() + "\t" + info.getThreadName()+"\t"); } }
Example 18
Source File: NativeProtocol.java From lams with GNU General Public License v2.0 | 4 votes |
private void appendDeadlockStatusInformation(Session sess, String xOpen, StringBuilder errorBuf) { if (sess.getPropertySet().getBooleanReadableProperty(PropertyDefinitions.PNAME_includeInnodbStatusInDeadlockExceptions).getValue() && xOpen != null && (xOpen.startsWith("40") || xOpen.startsWith("41")) && getStreamingData() == null) { try { NativePacketPayload resultPacket = sendCommand(this.commandBuilder.buildComQuery(getSharedSendPacket(), "SHOW ENGINE INNODB STATUS"), false, 0); Resultset rs = readAllResults(-1, false, resultPacket, false, null, new ResultsetFactory(Type.FORWARD_ONLY, null)); int colIndex = 0; Field f = null; for (int i = 0; i < rs.getColumnDefinition().getFields().length; i++) { f = rs.getColumnDefinition().getFields()[i]; if ("Status".equals(f.getName())) { colIndex = i; break; } } ValueFactory<String> vf = new StringValueFactory(f.getEncoding()); Row r; if ((r = rs.getRows().next()) != null) { errorBuf.append("\n\n").append(r.getValue(colIndex, vf)); } else { errorBuf.append("\n\n").append(Messages.getString("MysqlIO.NoInnoDBStatusFound")); } } catch (IOException | CJException ex) { errorBuf.append("\n\n").append(Messages.getString("MysqlIO.InnoDBStatusFailed")).append("\n\n").append(Util.stackTraceToString(ex)); } } if (sess.getPropertySet().getBooleanReadableProperty(PropertyDefinitions.PNAME_includeThreadDumpInDeadlockExceptions).getValue()) { errorBuf.append("\n\n*** Java threads running at time of deadlock ***\n\n"); ThreadMXBean threadMBean = ManagementFactory.getThreadMXBean(); long[] threadIds = threadMBean.getAllThreadIds(); ThreadInfo[] threads = threadMBean.getThreadInfo(threadIds, Integer.MAX_VALUE); List<ThreadInfo> activeThreads = new ArrayList<>(); for (ThreadInfo info : threads) { if (info != null) { activeThreads.add(info); } } for (ThreadInfo threadInfo : activeThreads) { // "Thread-60" daemon prio=1 tid=0x093569c0 nid=0x1b99 in Object.wait() errorBuf.append('"').append(threadInfo.getThreadName()).append("\" tid=").append(threadInfo.getThreadId()).append(" ") .append(threadInfo.getThreadState()); if (threadInfo.getLockName() != null) { errorBuf.append(" on lock=").append(threadInfo.getLockName()); } if (threadInfo.isSuspended()) { errorBuf.append(" (suspended)"); } if (threadInfo.isInNative()) { errorBuf.append(" (running in native)"); } StackTraceElement[] stackTrace = threadInfo.getStackTrace(); if (stackTrace.length > 0) { errorBuf.append(" in "); errorBuf.append(stackTrace[0].getClassName()).append("."); errorBuf.append(stackTrace[0].getMethodName()).append("()"); } errorBuf.append("\n"); if (threadInfo.getLockOwnerName() != null) { errorBuf.append("\t owned by ").append(threadInfo.getLockOwnerName()).append(" Id=").append(threadInfo.getLockOwnerId()).append("\n"); } for (int j = 0; j < stackTrace.length; j++) { StackTraceElement ste = stackTrace[j]; errorBuf.append("\tat ").append(ste.toString()).append("\n"); } } } }
Example 19
Source File: AEThreadMonitor.java From BiglyBT with GNU General Public License v2.0 | 4 votes |
private void dumpThreads( IndentWriter writer ) { final ThreadMXBean threadBean = ManagementFactory.getThreadMXBean(); long[] allThreadIds = threadBean.getAllThreadIds(); writer.println("Threads " + allThreadIds.length); writer.indent(); List<ThreadInfo> threadInfos = new ArrayList<>(allThreadIds.length); for (int i = 0; i < allThreadIds.length; i++) { ThreadInfo info = threadBean.getThreadInfo(allThreadIds[i], 32); if(info != null) threadInfos.add(info); } Collections.sort(threadInfos, new Comparator<ThreadInfo>() { @Override public int compare(ThreadInfo o1, ThreadInfo o2) { long diff = threadBean.getThreadCpuTime(o2.getThreadId()) - threadBean.getThreadCpuTime(o1.getThreadId()); if (diff == 0) { return o1.getThreadName().compareToIgnoreCase(o2.getThreadName()); } return diff > 0 ? 1 : -1; } }); for (int i = 0; i < threadInfos.size(); i++) { try { ThreadInfo threadInfo = threadInfos.get(i); long lCpuTime = threadBean.getThreadCpuTime(threadInfo.getThreadId()); if (lCpuTime == 0) break; String sState; switch (threadInfo.getThreadState()) { case BLOCKED: sState = "Blocked"; break; case RUNNABLE: sState = "Runnable"; break; case NEW: sState = "New"; break; case TERMINATED: sState = "Terminated"; break; case TIMED_WAITING: sState = "Timed Waiting"; break; case WAITING: sState = "Waiting"; break; default: sState = "" + threadInfo.getThreadState(); break; } String sName = threadInfo.getThreadName(); String sLockName = threadInfo.getLockName(); writer.println(sName + ": " + sState + ", " + (lCpuTime / 1000000) + "ms CPU, " + "B/W: " + threadInfo.getBlockedCount() + "/" + threadInfo.getWaitedCount() + (sLockName == null ? "" : "; Locked by " + sLockName + "/" + threadInfo.getLockOwnerName())); writer.indent(); try { StackTraceElement[] stackTrace = threadInfo.getStackTrace(); for (int j = 0; j < stackTrace.length; j++) { writer.println(stackTrace[j].toString()); } } finally { writer.exdent(); } } catch (Exception e) { // TODO: handle exception } } writer.exdent(); }
Example 20
Source File: ClientManager.java From OpenRate with Apache License 2.0 | 4 votes |
/** * getModuleList returns all the available client modules that have been * registered in the framework. * * @return StringBuffer - containing the client module symbolic names */ public StringBuffer getThreadList() { StringBuffer strThreadList = new StringBuffer(); long totalCpuTime = 0l; long totalUserTime = 0l; strThreadList.append( "OpenRate thread listing:\r\n+--------------------+------------------------------------+\r\n"); ThreadMXBean threads = ManagementFactory.getThreadMXBean(); strThreadList.append("current-thread-count <").append(threads.getThreadCount()).append(">\r\n"); strThreadList.append("total-started-thread-count <").append(threads.getTotalStartedThreadCount()).append(">\r\n"); strThreadList.append("daemon-thread-count <").append(threads.getDaemonThreadCount()).append(">\r\n"); strThreadList.append("peak-thread-count <").append(threads.getPeakThreadCount()).append(">\r\n"); // Parse each thread ThreadInfo[] threadInfos = threads.getThreadInfo(threads.getAllThreadIds()); for (int i = 0; i < threadInfos.length; i++) { strThreadList.append("id <").append(Long.toString(threadInfos[i].getThreadId())).append(">\r\n"); strThreadList.append("name <").append(threadInfos[i].getThreadName()).append(">\r\n"); strThreadList.append("cpu-time-nano <").append(Long.toString(threads.getThreadCpuTime(threadInfos[i].getThreadId()))).append(">\r\n"); strThreadList.append("cpu-time-ms <").append(Long.toString(threads.getThreadCpuTime(threadInfos[i].getThreadId()) / 1000000l)).append(">\r\n"); strThreadList.append("user-time-nano <").append(Long.toString(threads.getThreadUserTime(threadInfos[i].getThreadId()))).append(">\r\n"); strThreadList.append("user-time-ms <").append(Long.toString(threads.getThreadUserTime(threadInfos[i].getThreadId()) / 1000000l)).append(">\r\n"); strThreadList.append("blocked-count <").append(Long.toString(threadInfos[i].getBlockedCount())).append(">\r\n"); strThreadList.append("blocked-time <").append(Long.toString(threadInfos[i].getBlockedTime())).append(">\r\n"); strThreadList.append("waited-count <").append(Long.toString(threadInfos[i].getWaitedCount())).append(">\r\n"); strThreadList.append("waited-time <").append(Long.toString(threadInfos[i].getWaitedTime())).append(">\r\n"); strThreadList.append("+--------------------+\r\n"); // Update our aggregate values totalCpuTime += threads.getThreadCpuTime(threadInfos[ i].getThreadId()); totalUserTime += threads.getThreadUserTime(threadInfos[ i].getThreadId()); } long totalCpuTimeMs = totalCpuTime / 1000000l; long totalUserTimeMs = totalUserTime / 1000000l; strThreadList.append("total-cpu-time-nano <").append(Long.toString(totalCpuTime)).append(">\r\n"); strThreadList.append("total-user-time-nano <").append(Long.toString(totalUserTime)).append(">\r\n"); strThreadList.append("total-cpu-time-ms <").append(Long.toString(totalCpuTimeMs)).append(">\r\n"); strThreadList.append("total-user-time-ms <").append(Long.toString(totalUserTimeMs)).append(">\r\n"); strThreadList.append( "+--------------------+------------------------------------+"); return strThreadList; }