Example usage for java.lang.management ThreadMXBean getAllThreadIds

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

Introduction

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

Prototype

public long[] getAllThreadIds();

Source Link

Document

Returns all live thread IDs.

Usage

From source file:models.monitor.MonitorProvider.java

public ThreadUsage getThreadUsage() {
    ThreadMXBean threadMxBean = ManagementFactory.getThreadMXBean();
    ThreadUsage threadUsage = new ThreadUsage();
    long[] threadIds = threadMxBean.getAllThreadIds();
    threadUsage.liveThreadCount = threadIds.length;

    for (long tId : threadIds) {
        ThreadInfo threadInfo = threadMxBean.getThreadInfo(tId);
        threadUsage.threadData.put(new Long(tId).toString(), new ThreadData(threadInfo.getThreadName(),
                threadInfo.getThreadState().name(), threadMxBean.getThreadCpuTime(tId)));

    }/*from   www. j a v  a  2s .c o  m*/
    return threadUsage;
}

From source file:org.alfresco.extension.bulkimport.util.LogUtils.java

public final static String dumpThread(final String threadName) {
    final StringBuilder result = new StringBuilder();
    final ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean();
    final ThreadInfo[] threadsInfo = threadMXBean.getThreadInfo(threadMXBean.getAllThreadIds(), 100);

    for (final ThreadInfo threadInfo : threadsInfo) {
        if (threadName == null || threadName.equals(threadInfo.getThreadName())) {
            result.append("\nName: ");
            result.append(threadInfo.getThreadName());
            result.append("\nState: ");
            result.append(threadInfo.getThreadState());
            result.append("\nStack Trace:");

            for (final StackTraceElement stackTraceElement : threadInfo.getStackTrace()) {
                result.append("\n\t\tat ");
                result.append(stackTraceElement);
            }//w  ww  .  j  a  v a 2s  .  c o  m
        }
    }

    return (result.toString());
}

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

/**
 * Assert that there are no threads running whose name matches the
 * given regular expression.//from  www . j a  va  2 s .c  om
 * @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.
 *//*from www.  j av a 2  s  .  c o  m*/
@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++;//ww w . j a  va 2  s  .  c  o  m
        } 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
 *///www  .  j  a  v a  2s .  c o  m
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++;/* w ww . jav  a 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  ww  .java2  s  . c  om*/
        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 2s .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  ww . j ava 2 s  . 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();
}