Java Code Examples for java.lang.management.ThreadInfo

The following are top voted examples for showing how to use java.lang.management.ThreadInfo. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: jdk8u-jdk   File: TestThread.java   View source code 6 votes vote down vote up
/**
 * 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
Project: incubator-netbeans   File: NbTestCase.java   View source code 6 votes vote down vote up
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;
}
 
Example 3
Project: jdk8u-jdk   File: ThreadImpl.java   View source code 6 votes vote down vote up
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;
}
 
Example 4
Project: incubator-netbeans   File: SamplesOutputStream.java   View source code 6 votes vote down vote up
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));
        }
    }
}
 
Example 5
Project: dremio-oss   File: ThreadsIterator.java   View source code 6 votes vote down vote up
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();
}
 
Example 6
Project: jdk8u-jdk   File: ThreadInfoCompositeData.java   View source code 6 votes vote down vote up
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");
}
 
Example 7
Project: incubator-netbeans   File: ThreadDumpWindow.java   View source code 6 votes vote down vote up
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
}
 
Example 8
Project: incubator-netbeans   File: ThreadDumpWindow.java   View source code 6 votes vote down vote up
private void print15Thread(final StringBuilder sb, final ThreadInfo thread, boolean goToSourceAvailable) {
    sb.append("<br>\"" + thread.getThreadName() + // NOI18N
            "\" - Thread [email protected]" + thread.getThreadId() + "<br>");    // NOI18N
    sb.append("   java.lang.Thread.State: " + thread.getThreadState()); // NOI18N
    if (thread.getLockName() != null) {
        sb.append(" on " + thread.getLockName());   // NOI18N
        if (thread.getLockOwnerName() != null) {
            sb.append(" owned by: " + thread.getLockOwnerName());   // NOI18N
        }
    }
    sb.append("<br>");    // NOI18N
    for (StackTraceElement st : thread.getStackTrace()) {
        String stackElementText = htmlize(st.toString());
        String stackEl = stackElementText;
        if (goToSourceAvailable) {
            String className = st.getClassName();
            String method = st.getMethodName();
            int lineNo = st.getLineNumber();
            String stackUrl = OPEN_THREADS_URL + className + "|" + method + "|" + lineNo; // NOI18N
            stackEl = "<a href=\"" + stackUrl + "\">" + stackElementText + "</a>";    // NOI18N
        }
        sb.append("        at ").append(stackEl).append("<br>");    // NOI18N
    }
}
 
Example 9
Project: apache-tomcat-7.0.73-with-comment   File: Diagnostics.java   View source code 6 votes vote down vote up
/**
 * 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();
}
 
Example 10
Project: AgentWorkbench   File: LoadMeasureJVM.java   View source code 6 votes vote down vote up
/**
 * 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;		
}
 
Example 11
Project: openjdk-jdk10   File: GraalOSRLockTest.java   View source code 6 votes vote down vote up
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;
}
 
Example 12
Project: hadoop-oss   File: JvmMetrics.java   View source code 6 votes vote down vote up
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);
}
 
Example 13
Project: jdk8u-jdk   File: TestLogConfigurationDeadLock.java   View source code 6 votes vote down vote up
@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);
        }
    }
}
 
Example 14
Project: hadoop-oss   File: TestShell.java   View source code 6 votes vote down vote up
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;
}
 
Example 15
Project: hadoop-oss   File: TimedOutTestsListener.java   View source code 6 votes vote down vote up
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();
}
 
Example 16
Project: apache-tomcat-7.0.73-with-comment   File: Diagnostics.java   View source code 6 votes vote down vote up
/**
 * 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 "";
}
 
Example 17
Project: openjdk-jdk10   File: ConcurrentAssociateTest.java   View source code 6 votes vote down vote up
/**
 * 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 ------");
}
 
Example 18
Project: openjdk-jdk10   File: ThreadMXBeanStateTest.java   View source code 6 votes vote down vote up
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());
    }
}
 
Example 19
Project: openjdk-jdk10   File: ThreadImpl.java   View source code 6 votes vote down vote up
@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;
}
 
Example 20
Project: cornerstone   File: ThreadingManager.java   View source code 6 votes vote down vote up
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;
    }


}
 
Example 21
Project: tomcat7   File: Diagnostics.java   View source code 6 votes vote down vote up
/**
 * 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();
}
 
Example 22
Project: dremio-oss   File: ThreadsIterator.java   View source code 6 votes vote down vote up
@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));
}
 
Example 23
Project: openjdk-jdk10   File: LogManagerAppContextDeadlock.java   View source code 6 votes vote down vote up
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);
        }
    }
}
 
Example 24
Project: gate-core   File: ThreadWarningSystem.java   View source code 6 votes vote down vote up
/**
 * 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);
}
 
Example 25
Project: convertigo-engine   File: ThreadManager.java   View source code 6 votes vote down vote up
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;
}
 
Example 26
Project: openjdk-jdk10   File: TestLoggerBundleSync.java   View source code 6 votes vote down vote up
@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);
        }
    }
}
 
Example 27
Project: OpenJSharp   File: JvmThreadInstanceEntryImpl.java   View source code 6 votes vote down vote up
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;
}
 
Example 28
Project: jdk8u-jdk   File: TestLogConfigurationDeadLockWithConf.java   View source code 6 votes vote down vote up
@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);
        }
    }
}
 
Example 29
Project: yacy_grid_mcp   File: ThreaddumpService.java   View source code 5 votes vote down vote up
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);
        }
    }
}
 
Example 30
Project: yacy_grid_mcp   File: Memory.java   View source code 5 votes vote down vote up
/**
 * 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());
    }
}
 
Example 31
Project: Nukkit-Java9   File: Utils.java   View source code 5 votes vote down vote up
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();
}
 
Example 32
Project: incubator-netbeans   File: NbTestCase.java   View source code 5 votes vote down vote up
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");
    }
}
 
Example 33
Project: lazycat   File: Diagnostics.java   View source code 5 votes vote down vote up
/**
 * 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();
}
 
Example 34
Project: jdk8u-jdk   File: TestThread.java   View source code 5 votes vote down vote up
/**
 * 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) {
        }
    }
}
 
Example 35
Project: jdk8u-jdk   File: ThreadInfoCompositeData.java   View source code 5 votes vote down vote up
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);
}
 
Example 36
Project: incubator-netbeans   File: SampledCPUSnapshot.java   View source code 5 votes vote down vote up
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;
}
 
Example 37
Project: openjdk-jdk10   File: ThreadMXBeanTool.java   View source code 5 votes vote down vote up
/**
 * 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);
    }
}
 
Example 38
Project: openjdk-jdk10   File: JSR166TestCase.java   View source code 5 votes vote down vote up
/**
 * 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);
}
 
Example 39
Project: incubator-netbeans   File: ThreadDump.java   View source code 5 votes vote down vote up
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;
    }
}
 
Example 40
Project: jdk8u-jdk   File: ThreadImpl.java   View source code 5 votes vote down vote up
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);
}