Java Code Examples for java.lang.management.ThreadInfo

The following examples show how to use java.lang.management.ThreadInfo. These examples are extracted from open source projects. 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 want to check out the right sidebar which shows the related API usage.
Example 1
@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 2
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 3
@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 4
Source Project: hadoop-ozone   Source File: TimedOutTestsListener.java    License: Apache License 2.0 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 5
Source Project: hadoop-ozone   Source File: TimedOutTestsListener.java    License: Apache License 2.0 6 votes vote down vote up
private static void printThread(ThreadInfo ti, PrintWriter out) {
  out.print("\"" + ti.getThreadName() + "\"" + " Id="
      + ti.getThreadId() + " in " + ti.getThreadState());
  if (ti.getLockName() != null) {
    out.print(" on lock=" + ti.getLockName());
  }
  if (ti.isSuspended()) {
    out.print(" (suspended)");
  }
  if (ti.isInNative()) {
    out.print(" (running in native)");
  }
  out.println();
  if (ti.getLockOwnerName() != null) {
    out.println(INDENT + " owned by " + ti.getLockOwnerName() + " Id="
        + ti.getLockOwnerId());
  }
}
 
Example 6
@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 7
Source Project: TencentKona-8   Source File: ThreadImpl.java    License: GNU General Public License v2.0 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 8
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 9
Source Project: mapleLemon   Source File: DeadlockDetector.java    License: GNU General Public License v2.0 6 votes vote down vote up
private void printThread(ThreadInfo ti) {
    this.sb.append("\nPrintThread\n");
    this.sb.append("\"").append(ti.getThreadName()).append("\" Id=").append(ti.getThreadId()).append(" in ").append(ti.getThreadState()).append("\n");
    if (ti.getLockName() != null) {
        this.sb.append(" on lock=").append(ti.getLockName()).append("\n");
    }
    if (ti.isSuspended()) {
        this.sb.append(" (suspended)\n");
    }
    if (ti.isInNative()) {
        this.sb.append(" (running in native)\n");
    }
    if (ti.getLockOwnerName() != null) {
        this.sb.append(INDENT).append(" owned by ").append(ti.getLockOwnerName()).append(" Id=").append(ti.getLockOwnerId()).append("\n");
    }
}
 
Example 10
Source Project: jdk8u60   Source File: TestThread.java    License: GNU General Public License v2.0 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 11
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 12
public static void badTypeCompositeData() throws Exception {
    CompositeType ct =
        new CompositeType("MyCompositeType",
                          "CompositeType for ThreadInfo",
                          validItemNames,
                          validItemNames,
                          badItemTypes);

    // patch values[STACK_TRACE] to Long
    values[STACK_TRACE] = new Long(1000);
    values[LOCK_INFO] = new Long(1000);
    CompositeData cd =
        new CompositeDataSupport(ct,
                                 validItemNames,
                                 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 13
Source Project: distributedlog   Source File: TimedOutTestsListener.java    License: Apache License 2.0 6 votes vote down vote up
private static void printThread(ThreadInfo ti, PrintWriter out) {
    out.print("\"" + ti.getThreadName() + "\"" + " Id=" + ti.getThreadId() + " in " + ti.getThreadState());
    if (ti.getLockName() != null) {
        out.print(" on lock=" + ti.getLockName());
    }
    if (ti.isSuspended()) {
        out.print(" (suspended)");
    }
    if (ti.isInNative()) {
        out.print(" (running in native)");
    }
    out.println();
    if (ti.getLockOwnerName() != null) {
        out.println(indent + " owned by " + ti.getLockOwnerName() + " Id=" + ti.getLockOwnerId());
    }
}
 
Example 14
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 15
Source Project: Elasticsearch   Source File: DeadlockAnalyzer.java    License: Apache License 2.0 5 votes vote down vote up
private Deadlock[] createDeadlockDescriptions(Set<LinkedHashSet<ThreadInfo>> cycles) {
    Deadlock result[] = new Deadlock[cycles.size()];
    int count = 0;
    for (LinkedHashSet<ThreadInfo> cycle : cycles) {
        ThreadInfo asArray[] = cycle.toArray(new ThreadInfo[cycle.size()]);
        Deadlock d = new Deadlock(asArray);
        result[count++] = d;
    }
    return result;
}
 
Example 16
Source Project: Tomcat8-Source-Read   Source File: Diagnostics.java    License: MIT License 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 17
Source Project: attic-aurora   Source File: ContentionPrinter.java    License: Apache License 2.0 5 votes vote down vote up
private static List<String> getThreadInfo(ThreadInfo t, StackTraceElement[] stack) {
  List<String> lines = Lists.newLinkedList();

  lines.add(String.format("'%s' Id=%d %s",
      t.getThreadName(), t.getThreadId(), t.getThreadState()));
  lines.add("Waiting for lock: " + t.getLockName());
  lines.add("Lock is currently held by thread: " + t.getLockOwnerName());
  lines.add("Wait time: " + t.getBlockedTime() + " ms.");
  for (StackTraceElement s : stack) {
    lines.add(String.format("    " + s.toString()));
  }
  lines.add("\n");

  return lines;
}
 
Example 18
@Before
public void setUp() {
    instance = new StackTraceSnapshotBuilder();

    thread0 = new Thread("Test thread 0");
    thread1 = new Thread("Test thread 1");
    thread2 = new Thread("Test thread 2");
    
    stack0 = new java.lang.management.ThreadInfo[] {
            createThreadInfo(thread0, elements0),
            createThreadInfo(thread1, elements0)
    };

    stackPlus = new java.lang.management.ThreadInfo[] {
            createThreadInfo(thread0, elementsPlus),
            createThreadInfo(thread1, elements0),
            createThreadInfo(thread2, elements0)
    };

    stackMinus = new java.lang.management.ThreadInfo[] {
            createThreadInfo(thread0, elementsMinus)
    };

    stackDif = new java.lang.management.ThreadInfo[] {
            createThreadInfo(thread0, elementsDif)
    };

    stackDup = new java.lang.management.ThreadInfo[] {
            createThreadInfo(thread0, elementsDup),
            createThreadInfo(thread1, elements0)
    };

}
 
Example 19
public void record() {
    ThreadInfo[] threadInfos = threadMXBean.dumpAllThreads(false, false);
    DumpData dumpData = getCurrentDumpData(threadInfos);
    try {
        if (isFirstDump()) {
            return;
        }
        doRecordStackTraceData(threadInfos, dumpData);
    } finally {
        profilerData.setDumpData(dumpData);
    }
}
 
Example 20
Source Project: jdk8u-jdk   Source File: TestThread.java    License: GNU General Public License v2.0 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 21
Source Project: jdk8u-jdk   Source File: MappedMXBeanType.java    License: GNU General Public License v2.0 5 votes vote down vote up
Object toOpenTypeData(Object data) throws OpenDataException {
    if (data instanceof MemoryUsage) {
        return MemoryUsageCompositeData.toCompositeData((MemoryUsage) data);
    }

    if (data instanceof ThreadInfo) {
        return ThreadInfoCompositeData.toCompositeData((ThreadInfo) data);
    }

    if (data instanceof LockInfo) {
        if (data instanceof java.lang.management.MonitorInfo) {
            return MonitorInfoCompositeData.toCompositeData((MonitorInfo) data);
        }
        return LockInfoCompositeData.toCompositeData((LockInfo) data);
    }

    if (data instanceof MemoryNotificationInfo) {
        return MemoryNotifInfoCompositeData.
            toCompositeData((MemoryNotificationInfo) data);
    }

    if (data instanceof VMOption) {
        return VMOptionCompositeData.toCompositeData((VMOption) data);
    }

    if (isCompositeData) {
        // Classes that implement CompositeData
        //
        // construct a new CompositeDataSupport object
        // so that no other classes are sent over the wire
        CompositeData cd = (CompositeData) data;
        CompositeType ct = cd.getCompositeType();
        String[] itemNames = ct.keySet().toArray(new String[0]);
        Object[] itemValues = cd.getAll(itemNames);
        return new CompositeDataSupport(ct, itemNames, itemValues);
    }

    throw new OpenDataException(javaClass.getName() +
        " is not supported for platform MXBeans");
}
 
Example 22
Source Project: babar   Source File: StackTraceProfiler.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void sample(long sampleTimeMs, long deltaLastSampleMs) {
    for (ThreadInfo thread : getAllRunnableThreads()) {
        // certain threads do not have stack traceCache
        if (thread.getStackTrace().length > 0) {
            String traceKey = formatStackTrace(thread.getThreadName(), thread.getStackTrace());
            traceCache.increment(traceKey, sampleTimeMs);
        }
    }
}
 
Example 23
Source Project: ns4_gear_watchdog   Source File: HotThreadsMonitor.java    License: Apache License 2.0 5 votes vote down vote up
ThreadReport(ThreadInfo info, long cpuTime) {
    map.put(CPU_TIME, cpuTime);
    map.put(BLOCKED_COUNT, info.getBlockedCount());
    map.put(BLOCKED_TIME, info.getBlockedTime());
    map.put(WAITED_COUNT, info.getWaitedCount());
    map.put(WAITED_TIME, info.getWaitedTime());
    map.put(THREAD_NAME, info.getThreadName());
    map.put(THREAD_ID, info.getThreadId());
    map.put(THREAD_STATE, info.getThreadState().name().toLowerCase());
    map.put(THREAD_STACKTRACE, stackTraceAsString(info.getStackTrace()));
}
 
Example 24
Source Project: mapleLemon   Source File: DeadlockDetector.java    License: GNU General Public License v2.0 5 votes vote down vote up
@Override
public void run() {
    boolean noDeadLocks = true;

    while (noDeadLocks) {
        try {
            ThreadMXBean bean = ManagementFactory.getThreadMXBean();
            long[] threadIds = bean.findDeadlockedThreads();

            if (threadIds != null) {
                log.error("检测到死锁!!");
                this.sb = new StringBuilder();
                noDeadLocks = false;

                ThreadInfo[] infos = bean.getThreadInfo(threadIds);
                this.sb.append("\n线程锁信息: \n");
                for (ThreadInfo threadInfo : infos) {
                    printThreadInfo(threadInfo);
                    LockInfo[] lockInfos = threadInfo.getLockedSynchronizers();
                    MonitorInfo[] monitorInfos = threadInfo.getLockedMonitors();

                    printLockInfo(lockInfos);
                    printMonitorInfo(threadInfo, monitorInfos);
                }

                this.sb.append("\n线程转储: \n");
                for (ThreadInfo ti : bean.dumpAllThreads(true, true)) {
                    printThreadInfo(ti);
                }
                log.error(this.sb.toString());
            }
            Thread.sleep(this.checkInterval);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}
 
Example 25
Source Project: glowroot   Source File: Weaver.java    License: Apache License 2.0 5 votes vote down vote up
private void checkForDeadlockedActiveWeaving(List<Long> activeWeavingThreadIds) {
    ThreadMXBean threadBean = ManagementFactory.getThreadMXBean();
    long[] deadlockedThreadIds = threadBean.findDeadlockedThreads();
    if (deadlockedThreadIds == null || Collections.disjoint(Longs.asList(deadlockedThreadIds),
            activeWeavingThreadIds)) {
        return;
    }
    // need to disable weaving, otherwise getThreadInfo can trigger class loading and itself get
    // blocked by the deadlocked threads
    weavingDisabledForLoggingDeadlock = true;
    try {
        @Nullable
        ThreadInfo[] threadInfos = threadBean.getThreadInfo(deadlockedThreadIds,
                threadBean.isObjectMonitorUsageSupported(), false);
        StringBuilder sb = new StringBuilder();
        for (ThreadInfo threadInfo : threadInfos) {
            if (threadInfo != null) {
                sb.append('\n');
                appendThreadInfo(sb, threadInfo);
            }
        }
        logger.error("deadlock detected in class weaving, please report to the Glowroot"
                + " project:\n{}", sb);
        // no need to keep checking for (and logging) deadlocked active weaving
        throw new TerminateSubsequentExecutionsException();
    } finally {
        weavingDisabledForLoggingDeadlock = false;
    }
}
 
Example 26
Source Project: openjdk-8-source   Source File: ThreadImpl.java    License: GNU General Public License v2.0 5 votes vote down vote up
public ThreadInfo[] getThreadInfo(long[] ids,
                                  boolean lockedMonitors,
                                  boolean lockedSynchronizers) {
    verifyThreadIds(ids);
    verifyDumpThreads(lockedMonitors, lockedSynchronizers);
    return dumpThreads0(ids, lockedMonitors, lockedSynchronizers);
}
 
Example 27
private static ThreadInfo getThreadInfo(ThreadStateController t, Thread.State expected) {
    // wait for the thread to transition to the expected state.
    // There is a small window between the thread checking the state
    // and the thread actual entering that state.
    int retryCount=0;
    ThreadInfo info = tm.getThreadInfo(t.getId());
    while (info.getThreadState() != expected && retryCount < MAX_RETRY) {
        ThreadStateController.pause(10);
        retryCount++;
        info = tm.getThreadInfo(t.getId());
    }
    return info;
}
 
Example 28
Source Project: jdk8u-dev-jdk   Source File: ThreadMonitor.java    License: GNU General Public License v2.0 5 votes vote down vote up
private void dumpThreadInfo() {
   System.out.println("Full Java thread dump");
   long[] tids = tmbean.getAllThreadIds();
   ThreadInfo[] tinfos = tmbean.getThreadInfo(tids, Integer.MAX_VALUE);
   for (ThreadInfo ti : tinfos) {
       printThreadInfo(ti);
   }
}
 
Example 29
private void fireDeadlockDetected(ThreadInfo thread) {
  // In general I avoid using synchronized.  The surrounding
  // code should usually be responsible for being threadsafe.
  // However, in this case, the timer could be notifying at
  // the same time as someone is adding a listener, and there
  // is nothing the calling code can do to prevent that from
  // occurring.  Another tip though is this: when I synchronize
  // I use a private field to synchronize on, instead of
  // "this".
  synchronized (listeners) {
    for (Listener l : listeners) {
      l.deadlockDetected(thread);
    }
  }
}
 
Example 30
/**
 * Prints the thread dump information with locks info to System.out.
 */
private void dumpThreadInfoWithLocks() {
   System.out.println("Full Java thread dump with locks info");

   ThreadInfo[] tinfos = tmbean.dumpAllThreads(true, true);
   for (ThreadInfo ti : tinfos) {
       printThreadInfo(ti);
       LockInfo[] syncs = ti.getLockedSynchronizers();
       printLockInfo(syncs);
   }
   System.out.println();
}