Example usage for java.lang.management ThreadMXBean getThreadInfo

List of usage examples for java.lang.management ThreadMXBean getThreadInfo

Introduction

In this page you can find the example usage for java.lang.management ThreadMXBean getThreadInfo.

Prototype

public ThreadInfo[] getThreadInfo(long[] ids, int maxDepth);

Source Link

Document

Returns the thread info for each thread whose ID is in the input array ids , with stack trace of a specified number of stack trace elements.

Usage

From source file:org.apache.hadoop.hbase.GenericTestUtils.java

/**
 * Assert that there are no threads running whose name matches the
 * given regular expression./*  ww w . j av a2 s  .com*/
 * @param regex the regex to match against
 */
public static void assertNoThreadsMatching(String regex) {
    Pattern pattern = Pattern.compile(regex);
    ThreadMXBean threadBean = ManagementFactory.getThreadMXBean();

    ThreadInfo[] infos = threadBean.getThreadInfo(threadBean.getAllThreadIds(), 20);
    for (ThreadInfo info : infos) {
        if (info == null)
            continue;
        if (pattern.matcher(info.getThreadName()).matches()) {
            Assert.fail("Leaked thread: " + info + "\n" + Joiner.on("\n").join(info.getStackTrace()));
        }
    }
}

From source file:org.apache.hadoop.hdfs.server.namenode.ha.TestStandbyCheckpoints.java

/**
 * Test cancellation of ongoing checkpoints when failover happens
 * mid-checkpoint during image upload from standby to active NN.
 *//* ww w .  j  a va  2s .c  om*/
@Test(timeout = 60000)
public void testCheckpointCancellationDuringUpload() throws Exception {
    // don't compress, we want a big image
    cluster.getConfiguration(0).setBoolean(DFSConfigKeys.DFS_IMAGE_COMPRESS_KEY, false);
    cluster.getConfiguration(1).setBoolean(DFSConfigKeys.DFS_IMAGE_COMPRESS_KEY, false);
    // Throttle SBN upload to make it hang during upload to ANN
    cluster.getConfiguration(1).setLong(DFSConfigKeys.DFS_IMAGE_TRANSFER_RATE_KEY, 100);
    cluster.restartNameNode(0);
    cluster.restartNameNode(1);
    nn0 = cluster.getNameNode(0);
    nn1 = cluster.getNameNode(1);

    cluster.transitionToActive(0);

    doEdits(0, 100);
    HATestUtil.waitForStandbyToCatchUp(nn0, nn1);
    HATestUtil.waitForCheckpoint(cluster, 1, ImmutableList.of(104));
    cluster.transitionToStandby(0);
    cluster.transitionToActive(1);

    // Wait to make sure background TransferFsImageUpload thread was cancelled.
    // This needs to be done before the next test in the suite starts, so that a
    // file descriptor is not held open during the next cluster init.
    cluster.shutdown();
    cluster = null;
    GenericTestUtils.waitFor(new Supplier<Boolean>() {
        @Override
        public Boolean get() {
            ThreadMXBean threadBean = ManagementFactory.getThreadMXBean();
            ThreadInfo[] threads = threadBean.getThreadInfo(threadBean.getAllThreadIds(), 1);
            for (ThreadInfo thread : threads) {
                if (thread.getThreadName().startsWith("TransferFsImageUpload")) {
                    return false;
                }
            }
            return true;
        }
    }, 1000, 30000);

    // Assert that former active did not accept the canceled checkpoint file.
    assertEquals(0, nn0.getFSImage().getMostRecentCheckpointTxId());
}

From source file:org.apache.hadoop.metrics.jvm.JvmMetrics.java

private void doThreadUpdates() {
    ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean();
    long threadIds[] = threadMXBean.getAllThreadIds();
    ThreadInfo[] threadInfos = threadMXBean.getThreadInfo(threadIds, 0);

    int threadsNew = 0;
    int threadsRunnable = 0;
    int threadsBlocked = 0;
    int threadsWaiting = 0;
    int threadsTimedWaiting = 0;
    int threadsTerminated = 0;

    for (ThreadInfo threadInfo : threadInfos) {
        // threadInfo is null if the thread is not alive or doesn't exist
        if (threadInfo == null)
            continue;
        Thread.State state = threadInfo.getThreadState();
        if (state == NEW) {
            threadsNew++;/* www.  j av a 2s.  com*/
        } else if (state == RUNNABLE) {
            threadsRunnable++;
        } else if (state == BLOCKED) {
            threadsBlocked++;
        } else if (state == WAITING) {
            threadsWaiting++;
        } else if (state == TIMED_WAITING) {
            threadsTimedWaiting++;
        } else if (state == TERMINATED) {
            threadsTerminated++;
        }
    }
    metrics.setMetric("threadsNew", threadsNew);
    metrics.setMetric("threadsRunnable", threadsRunnable);
    metrics.setMetric("threadsBlocked", threadsBlocked);
    metrics.setMetric("threadsWaiting", threadsWaiting);
    metrics.setMetric("threadsTimedWaiting", threadsTimedWaiting);
    metrics.setMetric("threadsTerminated", threadsTerminated);
}

From source file:org.apache.hadoop.test.GenericTestUtils.java

/**
 * Determine if there are any threads whose name matches the regex.
 * @param pattern a Pattern object used to match thread names
 * @return true if there is any thread that matches the pattern
 *//*from   ww  w. jav  a  2  s . com*/
public static boolean anyThreadMatching(Pattern pattern) {
    ThreadMXBean threadBean = ManagementFactory.getThreadMXBean();

    ThreadInfo[] infos = threadBean.getThreadInfo(threadBean.getAllThreadIds(), 20);
    for (ThreadInfo info : infos) {
        if (info == null)
            continue;
        if (pattern.matcher(info.getThreadName()).matches()) {
            return true;
        }
    }
    return false;
}

From source file:org.apache.hadoop.util.TestShell.java

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++;//from  www .j ava 2 s  .c  om
                break;
            }
        }
    }
    return count;
}

From source file:org.apache.metron.common.utils.ErrorUtils.java

public 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("\n   java.lang.Thread.State: ");
        dump.append(state);/*from   w  w w .ja  va2s.  co m*/
        final StackTraceElement[] stackTraceElements = threadInfo.getStackTrace();
        for (final StackTraceElement stackTraceElement : stackTraceElements) {
            dump.append("\n        at ");
            dump.append(stackTraceElement);
        }
        dump.append("\n\n");
    }
    return dump.toString();
}

From source file:org.apache.servicemix.jbi.cluster.engine.AutoFailTestSupport.java

/**
 * Manually start the auto fail thread. To start it automatically, just set
 * the auto fail to true before calling any setup methods. As a rule, this
 * method is used only when you are not sure, if the setUp and tearDown
 * method is propagated correctly.//from   ww  w. ja  v a  2  s . c  o m
 */
public void startAutoFailThread() {
    setAutoFail(true);
    isTestSuccess = new AtomicBoolean(false);
    autoFailThread = new Thread(new Runnable() {
        public void run() {
            try {
                // Wait for test to finish succesfully
                Thread.sleep(getMaxTestTime());
            } catch (InterruptedException e) {
                // This usually means the test was successful
            } finally {
                // Check if the test was able to tear down succesfully,
                // which usually means, it has finished its run.
                if (!isTestSuccess.get()) {
                    LOG.error("Test case has exceeded the maximum allotted time to run of: " + getMaxTestTime()
                            + " ms.");
                    LOG.fatal("Test case has exceeded the maximum allotted time to run of: " + getMaxTestTime()
                            + " ms.");

                    if (LOG.isDebugEnabled()) {
                        ThreadMXBean threads = ManagementFactory.getThreadMXBean();
                        ThreadInfo[] threadInfos = threads.getThreadInfo(threads.getAllThreadIds(), 50);

                        for (ThreadInfo threadInfo : threadInfos) {
                            LOG.debug(threadInfo);
                        }
                    }

                    System.exit(EXIT_ERROR);
                }
            }
        }
    }, "AutoFailThread");

    if (verbose) {
        LOG.info("Starting auto fail thread...");
    }

    LOG.info("Starting auto fail thread...");
    autoFailThread.start();
}

From source file:org.apache.storm.utils.Utils.java

/**
 * Gets some information, including stack trace, for a running thread.
 * @return A human-readable string of the dump.
 *//*from   w  w  w .  j av  a 2s .c om*/
public static String threadDump() {
    final StringBuilder dump = new StringBuilder();
    final java.lang.management.ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean();
    final java.lang.management.ThreadInfo[] threadInfos = threadMXBean
            .getThreadInfo(threadMXBean.getAllThreadIds(), 100);
    for (java.lang.management.ThreadInfo threadInfo : threadInfos) {
        dump.append('"');
        dump.append(threadInfo.getThreadName());
        dump.append("\" ");
        dump.append("\n   lock: ");
        dump.append(threadInfo.getLockName());
        dump.append(" owner: ");
        dump.append(threadInfo.getLockOwnerName());
        final Thread.State state = threadInfo.getThreadState();
        dump.append("\n   java.lang.Thread.State: ");
        dump.append(state);
        final StackTraceElement[] stackTraceElements = threadInfo.getStackTrace();
        for (final StackTraceElement stackTraceElement : stackTraceElements) {
            dump.append("\n        at ");
            dump.append(stackTraceElement);
        }
        dump.append("\n\n");
    }
    return dump.toString();
}

From source file:org.apache.tajo.master.querymaster.QueryMasterRunner.java

public static void printThreadInfo(PrintWriter stream, String title) {
    ThreadMXBean threadBean = ManagementFactory.getThreadMXBean();
    final int STACK_DEPTH = 60;
    boolean contention = threadBean.isThreadContentionMonitoringEnabled();
    long[] threadIds = threadBean.getAllThreadIds();
    stream.println("Process Thread Dump: " + title);
    stream.println(threadIds.length + " active threads");
    for (long tid : threadIds) {
        ThreadInfo info = threadBean.getThreadInfo(tid, STACK_DEPTH);
        if (info == null) {
            stream.println("  Inactive");
            continue;
        }//ww w  .  j  a va2s . co  m
        stream.println("Thread " + getTaskName(info.getThreadId(), info.getThreadName()) + ":");
        Thread.State state = info.getThreadState();
        stream.println("  State: " + state);
        stream.println("  Blocked count: " + info.getBlockedCount());
        stream.println("  Waited count: " + info.getWaitedCount());
        if (contention) {
            stream.println("  Blocked time: " + info.getBlockedTime());
            stream.println("  Waited time: " + info.getWaitedTime());
        }
        if (state == Thread.State.WAITING) {
            stream.println("  Waiting on " + info.getLockName());
        } else if (state == Thread.State.BLOCKED) {
            stream.println("  Blocked on " + info.getLockName());
            stream.println("  Blocked by " + getTaskName(info.getLockOwnerId(), info.getLockOwnerName()));
        }
        stream.println("  Stack:");
        for (StackTraceElement frame : info.getStackTrace()) {
            stream.println("    " + frame.toString());
        }
    }
    stream.flush();
}

From source file:org.batoo.jpa.benchmark.BenchmarkTest.java

private void measureTimes(final ThreadMXBean mxBean, ArrayList<Runnable> profilingQueue) {
    final ThreadInfo[] threadInfos = mxBean.getThreadInfo(this.threadIds, Integer.MAX_VALUE);

    for (int i = 0; i < this.threadIds.length; i++) {
        final long id = this.threadIds[i];
        final ThreadInfo threadInfo = threadInfos[i];

        final long newThreadTime = mxBean.getThreadCpuTime(id);
        final long worked = Math.abs(newThreadTime - this.currentThreadTimes[i]);
        this.currentThreadTimes[i] = newThreadTime;

        profilingQueue.add(new Runnable() {

            @Override/*  ww w .j  a  v a2 s. c o m*/
            public void run() {
                BenchmarkTest.this.measureTime(worked, threadInfo);
            }
        });
    }
}