/** * 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) { } } }
private static StringBuilder printThread(ThreadInfo ti, StringBuilder sb) { sb.append("\"" + ti.getThreadName() + "\"" + " Id=" + ti.getThreadId() + " in " + ti.getThreadState()); if (ti.getLockName() != null) { sb.append(" waiting on lock=" + ti.getLockName()); } if (ti.isSuspended()) { sb.append(" (suspended)"); } if (ti.isInNative()) { sb.append(" (running in native)"); } sb.append("\n"); if (ti.getLockOwnerName() != null) { sb.append("\t owned by " + ti.getLockOwnerName() + " Id=" + ti.getLockOwnerId()).append("\n"); } return sb; }
public ThreadInfo[] getThreadInfo(long[] ids, int maxDepth) { verifyThreadIds(ids); if (maxDepth < 0) { throw new IllegalArgumentException( "Invalid maxDepth parameter: " + maxDepth); } // ids has been verified to be non-null // an empty array of ids should return an empty array of ThreadInfos if (ids.length == 0) return new ThreadInfo[0]; Util.checkMonitorAccess(); ThreadInfo[] infos = new ThreadInfo[ids.length]; // nulls if (maxDepth == Integer.MAX_VALUE) { getThreadInfo1(ids, -1, infos); } else { getThreadInfo1(ids, maxDepth, infos); } return infos; }
private void internStackTrace(ThreadInfo tinfo) { if (steCache == null) { return; } StackTraceElement[] stack = tinfo.getStackTrace(); for (int i = 0; i < stack.length; i++) { StackTraceElement ste = stack[i]; WeakReference<StackTraceElement> oldStackRef = steCache.get(ste); if (oldStackRef != null) { stack[i] = oldStackRef.get(); assert stack[i] != null; } else { steCache.put(ste, new WeakReference(ste)); } } }
public ThreadsIterator(final SabotContext dbContext, final OperatorContext context) { this.dbContext = dbContext; threadMXBean = ManagementFactory.getThreadMXBean(); final long[] ids = threadMXBean.getAllThreadIds(); final Iterator<Long> threadIdIterator = Longs.asList(ids).iterator(); this.threadInfoIterator = Iterators.filter( Iterators.transform(threadIdIterator, new Function<Long, ThreadInfo>() { @Override public ThreadInfo apply(Long input) { return threadMXBean.getThreadInfo(input, 100); } }), Predicates.notNull()); logger.debug("number of threads = {}, number of cores = {}", ids.length, NUMBER_OF_CORES); this.stats = dbContext.getWorkStatsProvider().get(); }
public static void badNameCompositeData() throws Exception { CompositeType ct = new CompositeType("MyCompositeType", "CompositeType for ThreadInfo", badItemNames, badItemNames, validItemTypes); CompositeData cd = new CompositeDataSupport(ct, badItemNames, values); try { ThreadInfo info = ThreadInfo.from(cd); } catch (IllegalArgumentException e) { System.out.println("Expected exception: " + e.getMessage()); return; } throw new RuntimeException( "IllegalArgumentException not thrown"); }
private void printThreads(final StringBuilder sb, ThreadDump td) { ThreadInfo[] threads = td.getThreads(); boolean goToSourceAvailable = GoToSource.isAvailable(); boolean jdk15 = td.isJDK15(); sb.append("<pre>"); // NOI18N sb.append(" <b>Full thread dump: "); // NOI18N SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); // NOI18N sb.append(df.format(td.getTime()) + "</b><br><br>"); for (ThreadInfo thread : threads) { if (thread != null) { if (jdk15) { print15Thread(sb, thread, goToSourceAvailable); } else { print16Thread(sb, thread, goToSourceAvailable); } } } sb.append("</pre>"); // NOI18N }
/** * Formats the thread dump header for one thread. * * @param ti the ThreadInfo describing the thread * @return the formatted thread dump header */ private static String getThreadDumpHeader(ThreadInfo ti) { StringBuilder sb = new StringBuilder("\"" + ti.getThreadName() + "\""); sb.append(" Id=" + ti.getThreadId()); sb.append(" cpu=" + threadMXBean.getThreadCpuTime(ti.getThreadId()) + " ns"); sb.append(" usr=" + threadMXBean.getThreadUserTime(ti.getThreadId()) + " ns"); sb.append(" blocked " + ti.getBlockedCount() + " for " + ti.getBlockedTime() + " ms"); sb.append(" waited " + ti.getWaitedCount() + " for " + ti.getWaitedTime() + " ms"); if (ti.isSuspended()) { sb.append(" (suspended)"); } if (ti.isInNative()) { sb.append(" (running in native)"); } sb.append(CRLF); sb.append(INDENT3 + "java.lang.Thread.State: " + ti.getThreadState()); sb.append(CRLF); return sb.toString(); }
/** * This method return true/false if a Thread, given by it's name exists or not. * @param threadName2LookAt the name of the thread * @return boolean true, if the named thread exists */ public boolean threadExists(String threadName2LookAt) { boolean exists = false; long[] jvmThreadIDs = threadXB.getAllThreadIds(); ThreadInfo[] jvmThreadInfo = threadXB.getThreadInfo(jvmThreadIDs); for (int i = 0; i < jvmThreadInfo.length; i++) { String threadName = jvmThreadInfo[i].getThreadName(); if (threadName.equalsIgnoreCase(threadName2LookAt)) { exists = true; break; } } return exists; }
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; }
private void getThreadUsage(MetricsRecordBuilder rb) { int threadsNew = 0; int threadsRunnable = 0; int threadsBlocked = 0; int threadsWaiting = 0; int threadsTimedWaiting = 0; int threadsTerminated = 0; long threadIds[] = threadMXBean.getAllThreadIds(); for (ThreadInfo threadInfo : threadMXBean.getThreadInfo(threadIds, 0)) { if (threadInfo == null) continue; // race protection switch (threadInfo.getThreadState()) { case NEW: threadsNew++; break; case RUNNABLE: threadsRunnable++; break; case BLOCKED: threadsBlocked++; break; case WAITING: threadsWaiting++; break; case TIMED_WAITING: threadsTimedWaiting++; break; case TERMINATED: threadsTerminated++; break; } } rb.addGauge(ThreadsNew, threadsNew) .addGauge(ThreadsRunnable, threadsRunnable) .addGauge(ThreadsBlocked, threadsBlocked) .addGauge(ThreadsWaiting, threadsWaiting) .addGauge(ThreadsTimedWaiting, threadsTimedWaiting) .addGauge(ThreadsTerminated, threadsTerminated); }
@Override public void run() { while(goOn) { try { long[] ids = ManagementFactory.getThreadMXBean().findDeadlockedThreads(); checkCount.incrementAndGet(); ids = ids == null ? new long[0] : 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); } } }
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; }
private static void printThreadInfo(ThreadInfo ti, PrintWriter out) { // print thread information printThread(ti, out); // print stack trace with locks StackTraceElement[] stacktrace = ti.getStackTrace(); MonitorInfo[] monitors = ti.getLockedMonitors(); for (int i = 0; i < stacktrace.length; i++) { StackTraceElement ste = stacktrace[i]; out.println(INDENT + "at " + ste.toString()); for (MonitorInfo mi : monitors) { if (mi.getLockedStackDepth() == i) { out.println(INDENT + " - locked " + mi); } } } out.println(); }
/** * Check if any threads are deadlocked. If any, print * the thread dump for those threads. * * @return a deadlock message and the formatted thread dump * of the deadlocked threads */ private static String findDeadlock() { ThreadInfo[] tinfos = null; long[] ids = threadMXBean.findDeadlockedThreads(); if (ids != null) { tinfos = threadMXBean.getThreadInfo(threadMXBean.findDeadlockedThreads(), true, true); if (tinfos != null) { StringBuilder sb = new StringBuilder("Deadlock found between the following threads:"); sb.append(CRLF); sb.append(getThreadDump(tinfos)); return sb.toString(); } } return ""; }
/** * 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 ------"); }
private static void checkSuspendedThreadState(ThreadStateController t, Thread.State state) { ThreadInfo info = getThreadInfo(t, state); if (info == null) { throw new RuntimeException(t.getName() + " expected to have ThreadInfo " + " but got null."); } if (info.getThreadState() != state) { throw new RuntimeException(t.getName() + " expected to be in " + state + " state but got " + info.getThreadState()); } if (!info.isSuspended()) { throw new RuntimeException(t.getName() + " expected to be suspended " + " but isSuspended() returns " + info.isSuspended()); } }
@Override public ThreadInfo[] getThreadInfo(long[] ids, int maxDepth) { verifyThreadIds(ids); if (maxDepth < 0) { throw new IllegalArgumentException( "Invalid maxDepth parameter: " + maxDepth); } // ids has been verified to be non-null // an empty array of ids should return an empty array of ThreadInfos if (ids.length == 0) return new ThreadInfo[0]; Util.checkMonitorAccess(); ThreadInfo[] infos = new ThreadInfo[ids.length]; // nulls if (maxDepth == Integer.MAX_VALUE) { getThreadInfo1(ids, -1, infos); } else { getThreadInfo1(ids, maxDepth, infos); } return infos; }
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; } }
@Override public Object next() { ThreadInfo currentThread = threadInfoIterator.next(); final NodeEndpoint endpoint = dbContext.getEndpoint(); final long id = currentThread.getThreadId(); return new ThreadSummary(endpoint.getAddress(), endpoint.getFabricPort(), currentThread.getThreadName(), currentThread.getThreadId(), currentThread.isInNative(), currentThread.isSuspended(), currentThread.getThreadState().name(), stats.getCpuTrailingAverage(id, 1), stats.getUserTrailingAverage(id, 1), NUMBER_OF_CORES, getStackTrace(currentThread)); }
public void loop() { while(goOn) { try { long[] ids = ManagementFactory.getThreadMXBean().findDeadlockedThreads(); ids = ids == null ? new long[0] : 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); } throw new DeadlockException("Found "+ids.length+" deadlocked threads"); } Thread.sleep(100); } catch(InterruptedException | RuntimeException x) { fail(x); } } }
/** * Monitor only deadlocks. */ public ThreadWarningSystem() { threadCheck.schedule(new TimerTask() { @Override public void run() { long[] ids = mbean.findMonitorDeadlockedThreads(); if (ids != null && ids.length > 0) { for (Long l : ids) { if (!deadlockedThreads.contains(l)) { deadlockedThreads.add(l); ThreadInfo ti = mbean.getThreadInfo(l, MAX_STACK_DEPTH); fireDeadlockDetected(ti); } } } } }, 10, DEADLOCK_CHECK_PERIOD); }
private String getThreadInfo(ThreadInfo ti) { String message = "\"" + ti.getThreadName() + "\" [ID=" + ti.getThreadId() + "]"; message += " is " + ti.getThreadState(); if (ti.isSuspended()) { message += " (suspended)"; } if (ti.isInNative()) { message += " (running in native)"; } message += ":\n"; if (ti.getLockName() != null) { message += INDENT + "waiting to lock " + ti.getLockName() + "\n"; } if (ti.getLockOwnerName() != null) { message += INDENT + "owned by \"" + ti.getLockOwnerName() + "\" [ID=" + ti.getLockOwnerId() + "]\n"; } return message; }
@Override public void run() { while(goOn) { try { long[] ids = ManagementFactory.getThreadMXBean().findDeadlockedThreads(); checkCount.incrementAndGet(); ids = ids == null ? new long[0] : 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); 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); } } }
public static Byte[] getState(ThreadInfo info) { byte[] bitmap = new byte[] {(byte)0x00, (byte)0x00}; try { final Thread.State state = info.getThreadState(); final boolean inNative = info.isInNative(); final boolean suspended = info.isSuspended(); log.debug("getJvmThreadInstState", "[State=" + state + ",isInNative=" + inNative + ",isSuspended=" + suspended + "]"); setState(bitmap,state); if (inNative) setNative(bitmap); if (suspended) setSuspended(bitmap); checkOther(bitmap); } catch (RuntimeException r) { bitmap[0]=(byte)0x00; bitmap[1]=Byte1.other; log.trace("getJvmThreadInstState", "Unexpected exception: " + r); log.debug("getJvmThreadInstState",r); } Byte[] result = { new Byte(bitmap[0]), new Byte(bitmap[1]) }; return result; }
@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); } } }
private ThreadDump( final Map<Thread, StackTraceElement[]> stackTraces, final Thread.State stateIn) { super(); Thread thread; // collect single dumps for (final Map.Entry<Thread, StackTraceElement[]> entry: stackTraces.entrySet()) { thread = entry.getKey(); final StackTraceElement[] stackTraceElements = entry.getValue(); StackTraceElement ste; String tracename = ""; final State threadState = thread.getState(); final ThreadInfo info = Memory.threadBean.getThreadInfo(thread.getId()); if (threadState != null && info != null && (stateIn == null || stateIn.equals(threadState)) && stackTraceElements.length > 0) { final StringBuilder sb = new StringBuilder(3000); final String threadtitle = tracename + "THREAD: " + thread.getName() + " " + (thread.isDaemon()?"daemon":"") + " id=" + thread.getId() + " " + threadState.toString() + (info.getLockOwnerId() >= 0 ? " lock owner =" + info.getLockOwnerId() : ""); boolean cutcore = true; for (int i = 0; i < stackTraceElements.length; i++) { ste = stackTraceElements[i]; String className = ste.getClassName(); String classString = ste.toString(); if (cutcore && (className.startsWith("java.") || className.startsWith("sun."))) { sb.setLength(0); bufferappend(sb, tracename + "at " + classString); } else { cutcore = false; bufferappend(sb, tracename + "at " + classString); } } final StackTrace stackTrace = new StackTrace(sb.toString()); SortedSet<String> threads = get(stackTrace); if (threads == null) { threads = new TreeSet<String>(); put(stackTrace, threads); } threads.add(threadtitle); } } }
/** * write deadlocked threads as to the log as warning */ public static void logDeadlocks() { long[] deadlockIDs = ManagementFactory.getThreadMXBean().findDeadlockedThreads(); if (deadlockIDs == null) return; ThreadInfo[] infos = ManagementFactory.getThreadMXBean().getThreadInfo(deadlockIDs, true, true); for (ThreadInfo ti : infos) { Data.logger.warn("DEADLOCKREPORT: " + ti.toString()); } }
public static String getAllThreadDumps() { ThreadInfo[] threads = ManagementFactory.getThreadMXBean().dumpAllThreads(true, true); StringBuilder builder = new StringBuilder(); for (ThreadInfo info : threads) { builder.append('\n').append(info); } return builder.toString(); }
private static void printMonitorInfo(ThreadInfo ti, MonitorInfo[] monitors, StringBuilder sb) { sb.append("\tLocked monitors: count = " + monitors.length).append("\n"); for (MonitorInfo mi : monitors) { sb.append("\t - " + mi + " locked at ").append("\n"); sb.append("\t " + mi.getLockedStackDepth() + " " + mi.getLockedStackFrame()).append("\n"); } }
/** * Formats the thread dump for a list of threads. * * @param tinfos * the ThreadInfo array describing the thread list * @return the formatted thread dump */ private static String getThreadDump(ThreadInfo[] tinfos) { StringBuilder sb = new StringBuilder(); for (ThreadInfo tinfo : tinfos) { sb.append(getThreadDump(tinfo)); sb.append(CRLF); } return sb.toString(); }
/** * Waits until {@link TestThread} is in native. */ public void waitUntilInNative() { ThreadMXBean tmx = ManagementFactory.getThreadMXBean(); while (isAlive()) { ThreadInfo ti = tmx.getThreadInfo(getId()); if (ti.isInNative()) { return; } try { Thread.sleep(1); } catch (InterruptedException e) { } } }
public static void createGoodCompositeData() throws Exception { CompositeType ct = new CompositeType("MyCompositeType", "CompositeType for ThreadInfo", validItemNames, validItemNames, validItemTypes); CompositeData cd = new CompositeDataSupport(ct, validItemNames, values); ThreadInfo info = ThreadInfo.from(cd); checkThreadInfo(info); }
public long getValue(int sampleIndex, int valIndex) throws IOException { getSample(sampleIndex); long ret = 0; for (ThreadInfo info : sample.getTinfos()) { if (info.getThreadState().equals(Thread.State.RUNNABLE)) { ret += info.getStackTrace().length; } } return ret; }
/** * 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); } }
/** * A debugging tool to print stack traces of most threads, as jstack does. * Uninteresting threads are filtered out. */ static void dumpTestThreads() { SecurityManager sm = System.getSecurityManager(); if (sm != null) { try { System.setSecurityManager(null); } catch (SecurityException giveUp) { return; } } ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean(); System.err.println("------ stacktrace dump start ------"); for (ThreadInfo info : threadMXBean.dumpAllThreads(true, true)) { final String name = info.getThreadName(); String lockName; if ("Signal Dispatcher".equals(name)) continue; if ("Reference Handler".equals(name) && (lockName = info.getLockName()) != null && lockName.startsWith("java.lang.ref.Reference$Lock")) continue; if ("Finalizer".equals(name) && (lockName = info.getLockName()) != null && lockName.startsWith("java.lang.ref.ReferenceQueue$Lock")) continue; if ("checkForWedgedTest".equals(name)) continue; System.err.print(info); } System.err.println("------ stacktrace dump end ------"); if (sm != null) System.setSecurityManager(sm); }
public ThreadInfo[] getThreads() { synchronized (tinfoLock) { if (tinfos == null) { int i = 0; tinfos = new ThreadInfo[cdThreads.length]; for (Object cd : cdThreads) { tinfos[i++] = ThreadInfo.from((CompositeData) cd); } cdThreads = null; } return tinfos; } }
public ThreadInfo[] getThreadInfo(long[] ids, boolean lockedMonitors, boolean lockedSynchronizers) { verifyThreadIds(ids); // ids has been verified to be non-null // an empty array of ids should return an empty array of ThreadInfos if (ids.length == 0) return new ThreadInfo[0]; verifyDumpThreads(lockedMonitors, lockedSynchronizers); return dumpThreads0(ids, lockedMonitors, lockedSynchronizers); }