Example usage for java.lang.management ManagementFactory getThreadMXBean

List of usage examples for java.lang.management ManagementFactory getThreadMXBean

Introduction

In this page you can find the example usage for java.lang.management ManagementFactory getThreadMXBean.

Prototype

public static ThreadMXBean getThreadMXBean() 

Source Link

Document

Returns the managed bean for the thread system of the Java virtual machine.

Usage

From source file:org.commonjava.indy.diag.data.DiagnosticsManager.java

public String getThreadDumpString() {
    Thread[] threads = new Thread[Thread.activeCount()];
    Thread.enumerate(threads);// w ww  .ja  v  a 2s .co  m

    Map<Long, Thread> threadMap = new HashMap<>();
    Stream.of(threads).forEach(t -> threadMap.put(t.getId(), t));
    ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean();
    ThreadInfo[] threadInfos = threadMXBean.getThreadInfo(threadMXBean.getAllThreadIds(), 100);

    StringBuilder sb = new StringBuilder();
    Stream.of(threadInfos).forEachOrdered((ti) -> {
        if (sb.length() > 0) {
            sb.append("\n\n");
        }

        String threadGroup = "Unknown";
        Thread t = threadMap.get(ti.getThreadId());
        if (t != null) {
            ThreadGroup tg = t.getThreadGroup();
            if (tg != null) {
                threadGroup = tg.getName();
            }
        }

        sb.append(ti.getThreadName()).append("\n  Group: ").append(threadGroup).append("\n  State: ")
                .append(ti.getThreadState()).append("\n  Lock Info: ").append(ti.getLockInfo())
                .append("\n  Monitors:");

        MonitorInfo[] monitors = ti.getLockedMonitors();
        if (monitors == null || monitors.length < 1) {
            sb.append("  -NONE-");
        } else {
            sb.append("\n  - ").append(join(monitors, "\n  - "));
        }

        sb.append("\n  Trace:\n    ").append(join(ti.getStackTrace(), "\n    "));

    });

    return sb.toString();
}

From source file:org.talend.dataquality.statistics.datetime.PerformanceTest.java

@Test
@Ignore// w  w w . j  a  v  a2s.c o  m
public void testGetPatterns() throws IOException {

    final InputStream stream = SystemDateTimePatternManager.class.getResourceAsStream("DateSampleTable.txt");
    final List<String> lines = IOUtils.readLines(stream);

    SystemDateTimePatternManager.datePatternReplace("12/02/99");// init DateTimeFormatters

    final ThreadMXBean mxBean = ManagementFactory.getThreadMXBean();
    final long cpuBefore = mxBean.getCurrentThreadCpuTime();

    int count = 0;
    loop: for (int n = 0; n < REPLICATE; n++) {
        for (int i = 1; i < lines.size(); i++) {
            final String line = lines.get(i);
            if (!"".equals(line.trim())) {
                final String[] sampleLine = line.trim().split("\t");
                final String sample = sampleLine[0];
                SystemDateTimePatternManager.datePatternReplace(sample);
                count++;
                if (count > 100000) {
                    break loop;
                }
            }
        }
    }

    final long cpuAfter = mxBean.getCurrentThreadCpuTime();

    final long difference = cpuAfter - cpuBefore;
    assertTrue("The method getPatterns() is slower than expected. Actual CPU time spent: " + difference,
            difference < 25e8);
}

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 ww  w  .  j a v a 2 s .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:serposcope.controllers.admin.AdminController.java

public Result stackdump(Context context) {

    return Results.contentType("text/plain").render((ctx, res) -> {
        ResponseStreams responseStreams = context.finalizeHeaders(res);
        try (PrintWriter writer = new PrintWriter(responseStreams.getOutputStream());) {
            final ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean();
            final ThreadInfo[] threadInfos = threadMXBean.getThreadInfo(threadMXBean.getAllThreadIds(), 100);
            for (ThreadInfo threadInfo : threadInfos) {
                writer.append('"');
                writer.append(threadInfo.getThreadName());
                writer.append("\" ");
                final Thread.State state = threadInfo.getThreadState();
                writer.append("\n   java.lang.Thread.State: ");
                writer.append(state.toString());
                final StackTraceElement[] stackTraceElements = threadInfo.getStackTrace();
                for (final StackTraceElement stackTraceElement : stackTraceElements) {
                    writer.append("\n        at ");
                    writer.append(stackTraceElement.toString());
                }//  w w  w . ja  va  2 s  . c  o  m
                writer.println("\n");
            }
        } catch (IOException ex) {
            LOG.error("stackdump", ex);
        }
    });
}

From source file:org.apache.bookkeeper.common.testing.util.TimedOutTestsListener.java

static String buildDeadlockInfo() {
    ThreadMXBean threadBean = ManagementFactory.getThreadMXBean();
    long[] threadIds = threadBean.findMonitorDeadlockedThreads();
    if (threadIds != null && threadIds.length > 0) {
        StringWriter stringWriter = new StringWriter();
        PrintWriter out = new PrintWriter(stringWriter);

        ThreadInfo[] infos = threadBean.getThreadInfo(threadIds, true, true);
        for (ThreadInfo ti : infos) {
            printThreadInfo(ti, out);//www .  j av  a2 s. com
            printLockInfo(ti.getLockedSynchronizers(), out);
            out.println();
        }

        out.close();
        return stringWriter.toString();
    } else {
        return null;
    }
}

From source file:metlos.executors.batch.BatchCpuThrottlingExecutorTest.java

@Test
public void maxUsage_SingleThreaded() throws Exception {
    NamingThreadFactory factory = new NamingThreadFactory();
    ThreadPoolExecutor e = new ThreadPoolExecutor(1, 1, 0, TimeUnit.DAYS, new LinkedBlockingQueue<Runnable>(),
            factory);/* w ww.  ja v a2  s  . c  om*/
    e.prestartAllCoreThreads();

    List<Future<?>> payloadResults = new ArrayList<Future<?>>();

    long startTime = System.nanoTime();

    //create load
    for (int i = 0; i < NOF_JOBS; ++i) {
        Future<?> f = e.submit(new Payload());
        payloadResults.add(f);
    }

    //wait for it all to finish
    for (Future<?> f : payloadResults) {
        f.get();
    }

    long endTime = System.nanoTime();

    long time = endTime - startTime;
    LOG.info("MAX Singlethreaded test took " + (time / 1000.0 / 1000.0) + "ms");

    ThreadMXBean threadBean = ManagementFactory.getThreadMXBean();
    long cpuTime = 0;
    for (Thread t : factory.createdThreads) {
        long threadCpuTime = threadBean.getThreadCpuTime(t.getId());
        LOG.info(t.getName() + ": " + threadCpuTime + "ns");
        cpuTime += threadCpuTime;
    }

    float actualUsage = (float) cpuTime / time;

    LOG.info("MAX Singlethreaded overall usage: " + actualUsage);
}

From source file:com.rest4j.impl.UtilTest.java

@Test
public void testClone() {
    Tree test = new Tree();
    test.name = StringUtils.repeat("TEST", 10000);
    test.left = new Tree();
    test.right = test.left;/*  w ww . j  a  v  a2 s  . c om*/

    ThreadMXBean threadMx = ManagementFactory.getThreadMXBean();
    long start = threadMx.getCurrentThreadCpuTime();
    int N = 10000;
    for (int i = 0; i < N; i++)
        test = Util.deepClone(test);
    System.out.println("cloned in " + (threadMx.getCurrentThreadCpuTime() - start) / N + "ns");
    assertSame(test.left, test.right);
}

From source file:models.monitor.MonitorProvider.java

public ThreadInfo[] getThreadDump() {
    ThreadMXBean threadMxBean = ManagementFactory.getThreadMXBean();
    return threadMxBean.dumpAllThreads(true, true);
}

From source file:com.thoughtworks.go.server.service.builders.KillAllChildProcessTaskBuilderTest.java

public long getSystemTime() {
    ThreadMXBean bean = ManagementFactory.getThreadMXBean();
    return bean.isCurrentThreadCpuTimeSupported()
            ? (bean.getCurrentThreadCpuTime() - bean.getCurrentThreadUserTime())
            : 0L;// w  w w . j  a va2 s. c o  m
}

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  www  . j  ava2 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();
}