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:com.eurelis.opencms.admin.systeminformation.CmsSystemInformationOverviewDialog.java

/**
 * Initializes the infos object.<p>
 *//*w ww. j a  v  a 2s. c  o m*/
protected void initInfosObject() {

    com.sun.management.OperatingSystemMXBean sunOsBean = (com.sun.management.OperatingSystemMXBean) ManagementFactory
            .getOperatingSystemMXBean();
    java.lang.management.OperatingSystemMXBean osBean = ManagementFactory.getOperatingSystemMXBean();
    java.lang.management.ThreadMXBean threadBean = ManagementFactory.getThreadMXBean();
    java.lang.management.RuntimeMXBean runtimeBean = ManagementFactory.getRuntimeMXBean();
    java.lang.management.ClassLoadingMXBean classesBean = ManagementFactory.getClassLoadingMXBean();

    //JVM uptime
    Date date = new Date(runtimeBean.getUptime());
    java.text.SimpleDateFormat simpleFormatH = new java.text.SimpleDateFormat("HH");
    java.text.SimpleDateFormat simpleFormatM = new java.text.SimpleDateFormat("mm");
    java.text.SimpleDateFormat simpleFormatS = new java.text.SimpleDateFormat("ss");
    String jvmuptimestring = simpleFormatH.format(date) + "h " + simpleFormatM.format(date) + "min "
            + simpleFormatS.format(date) + "s ";

    //JVM start time
    date = new Date(runtimeBean.getStartTime());
    String jvmstarttimestring = simpleFormatH.format(date) + "h " + simpleFormatM.format(date) + "min "
            + simpleFormatS.format(date) + "s ";

    //OpenCms runtime
    date = new Date(OpenCms.getSystemInfo().getRuntime());
    String opencmsruntimestring = simpleFormatH.format(date) + "h " + simpleFormatM.format(date) + "min "
            + simpleFormatS.format(date) + "s ";

    //OpenCms startup time
    date = new Date(OpenCms.getSystemInfo().getStartupTime());
    String opencmsstartuptimestring = simpleFormatH.format(date) + "h " + simpleFormatM.format(date) + "min "
            + simpleFormatS.format(date) + "s ";

    setOperatingSystem("" + osBean.getName());
    setJavaVersion(System.getProperty("java.version"));
    setJvmUptime("" + jvmuptimestring);
    setJvmStarttime("" + jvmstarttimestring);
    setOpenCmsVersion(OpenCms.getSystemInfo().getVersionNumber());
    setOpenCmsRuntime("" + opencmsruntimestring);
    setOpenCmsStartupTime("" + opencmsstartuptimestring);

    Object o;
    if (CmsStringUtil.isEmpty(getParamAction())) {
        o = new CmsAdminSettings(getSession());
    } else {
        // this is not the initial call, get the job object from session
        o = getDialogObject();
    }
    if (!(o instanceof CmsAdminSettings)) {
        // create a new history settings handler object
        m_adminSettings = new CmsAdminSettings(getSession());
    } else {
        // reuse html import handler object stored in session
        m_adminSettings = (CmsAdminSettings) o;
    }

}

From source file:com.alibaba.druid.benckmark.pool.Case1.java

private void p0(final DataSource dataSource, String name, int threadCount) throws Exception {

    final CountDownLatch startLatch = new CountDownLatch(1);
    final CountDownLatch endLatch = new CountDownLatch(threadCount);
    final CountDownLatch dumpLatch = new CountDownLatch(1);

    Thread[] threads = new Thread[threadCount];
    for (int i = 0; i < threadCount; ++i) {
        Thread thread = new Thread() {

            public void run() {
                try {
                    startLatch.await();/*  w w w. ja  v  a 2  s.  c  o m*/

                    for (int i = 0; i < LOOP_COUNT; ++i) {
                        Connection conn = dataSource.getConnection();
                        conn.close();
                    }
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
                endLatch.countDown();

                try {
                    dumpLatch.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        };
        threads[i] = thread;
        thread.start();
    }
    long startMillis = System.currentTimeMillis();
    long startYGC = TestUtil.getYoungGC();
    long startFullGC = TestUtil.getFullGC();
    startLatch.countDown();
    endLatch.await();

    long[] threadIdArray = new long[threads.length];
    for (int i = 0; i < threads.length; ++i) {
        threadIdArray[i] = threads[i].getId();
    }
    ThreadInfo[] threadInfoArray = ManagementFactory.getThreadMXBean().getThreadInfo(threadIdArray);

    dumpLatch.countDown();

    long blockedCount = 0;
    long waitedCount = 0;
    for (int i = 0; i < threadInfoArray.length; ++i) {
        ThreadInfo threadInfo = threadInfoArray[i];
        blockedCount += threadInfo.getBlockedCount();
        waitedCount += threadInfo.getWaitedCount();
    }

    long millis = System.currentTimeMillis() - startMillis;
    long ygc = TestUtil.getYoungGC() - startYGC;
    long fullGC = TestUtil.getFullGC() - startFullGC;

    System.out.println("thread " + threadCount + " " + name + " millis : "
            + NumberFormat.getInstance().format(millis) + "; YGC " + ygc + " FGC " + fullGC + " blocked "
            + NumberFormat.getInstance().format(blockedCount) //
            + " waited " + NumberFormat.getInstance().format(waitedCount) + " physicalConn "
            + physicalConnStat.get());

}

From source file:com.thoughtworks.go.server.service.support.ThreadInformationProvider.java

@Override
public Map<String, Object> asJson() {
    ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean();
    LinkedHashMap<String, Object> json = new LinkedHashMap<>();
    json.put("Thread Count", getThreadCount(threadMXBean));
    json.put("DeadLock Threads", getDeadLockThreadInformation(threadMXBean));
    json.put("Stack Trace", getStackTraceInformation(threadMXBean));
    return json;/*from w  w w  .  j  a  va 2 s . com*/
}

From source file:com.pikai.jdbc.testcase.PoolTest.java

private void p0(final DataSource dataSource, String name, int threadCount) throws Exception {

    final CountDownLatch startLatch = new CountDownLatch(1);
    final CountDownLatch endLatch = new CountDownLatch(threadCount);
    final CountDownLatch dumpLatch = new CountDownLatch(1);

    Thread[] threads = new Thread[threadCount];
    for (int i = 0; i < threadCount; ++i) {
        Thread thread = new Thread() {
            public void run() {
                try {
                    startLatch.await();//from   ww w .  j ava 2s . c  om

                    for (int i = 0; i < LOOP_COUNT; ++i) {
                        Connection conn = dataSource.getConnection();
                        conn.close();
                    }
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
                endLatch.countDown();

                try {
                    dumpLatch.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        };
        threads[i] = thread;
        thread.start();
    }
    long startMillis = System.currentTimeMillis();
    long startYGC = TestUtil.getYoungGC();
    long startFullGC = TestUtil.getFullGC();
    startLatch.countDown();
    endLatch.await();

    long[] threadIdArray = new long[threads.length];
    for (int i = 0; i < threads.length; ++i) {
        threadIdArray[i] = threads[i].getId();
    }
    ThreadInfo[] threadInfoArray = ManagementFactory.getThreadMXBean().getThreadInfo(threadIdArray);

    dumpLatch.countDown();

    long blockedCount = 0;
    long waitedCount = 0;
    for (int i = 0; i < threadInfoArray.length; ++i) {
        ThreadInfo threadInfo = threadInfoArray[i];
        blockedCount += threadInfo.getBlockedCount();
        waitedCount += threadInfo.getWaitedCount();
    }

    long millis = System.currentTimeMillis() - startMillis;
    long ygc = TestUtil.getYoungGC() - startYGC;
    long fullGC = TestUtil.getFullGC() - startFullGC;

    System.out.println("thread " + threadCount + " " + name + " millis : "
            + NumberFormat.getInstance().format(millis) + "; YGC " + ygc + " FGC " + fullGC + " blocked "
            + NumberFormat.getInstance().format(blockedCount) //
            + " waited " + NumberFormat.getInstance().format(waitedCount) + " physicalConn "
            + physicalConnStat.get());

}

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 va2  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.kaaproject.kaa.server.common.thrift.cli.server.BaseCliThriftService.java

/**
 * Dump service threads information./*from w  w w . j  a va2  s. com*/
 *
 * @param writer the writer to output threads information
 */
private void dumpThreads(PrintWriter writer) {
    writer.println("THREADS DUMP:");
    writer.println();

    ThreadMXBean threadMxBean = ManagementFactory.getThreadMXBean();
    ThreadInfo[] threads = threadMxBean.dumpAllThreads(false, false);
    Map<Long, ThreadStruct> threadsMap = new HashMap<>();
    for (ThreadInfo ti : threads) {
        ThreadStruct ts = new ThreadStruct();
        ts.ti = ti;
        threadsMap.put(ti.getThreadId(), ts);
    }

    ThreadGroup root = Thread.currentThread().getThreadGroup();

    ThreadGroup parent;
    parent = root.getParent();
    while (parent != null) {
        root = parent;
        parent = parent.getParent();
    }
    allThreadsFromGroup(root, threadsMap);

    Collection<ThreadStruct> threadValues = threadsMap.values();
    List<ThreadStruct> threadList = new ArrayList<>(threadValues);

    Collections.sort(threadList);

    Map<State, Integer> threadStatistics = new LinkedHashMap<>();
    threadStatistics.put(State.NEW, 0);
    threadStatistics.put(State.RUNNABLE, 0);
    threadStatistics.put(State.BLOCKED, 0);
    threadStatistics.put(State.WAITING, 0);
    threadStatistics.put(State.TIMED_WAITING, 0);
    threadStatistics.put(State.TERMINATED, 0);
    int maxGroup = 0;
    int maxName = 0;
    for (ThreadStruct thread : threadList) {
        maxName = Math.max(thread.ti.getThreadName().length(), maxName);
        maxGroup = Math.max(thread.getGroupName().length(), maxGroup);
        int count = threadStatistics.get(thread.ti.getThreadState());
        count++;
        threadStatistics.put(thread.ti.getThreadState(), count);
    }

    StringBuffer header = new StringBuffer();
    header.append("ID");
    int idColumnLength = 4;
    int length = idColumnLength;
    header.append(createPadding(length - header.length()));
    header.append("GROUP");
    int groupColumnLength = maxGroup + 1;
    length += groupColumnLength;
    header.append(createPadding(length - header.length()));
    header.append("NAME");
    int nameColumnLength = maxName + 1;
    length += nameColumnLength;
    header.append(createPadding(length - header.length()));
    header.append("PRIORITY");
    int priorityColumnLength = 10;
    length += priorityColumnLength;
    header.append(createPadding(length - header.length()));
    header.append("STATE");
    int stateColumnLength = 14;
    length += stateColumnLength;
    header.append(createPadding(length - header.length()));
    header.append("DAEMON");
    int daemonColumnLengh = 7;
    length += daemonColumnLengh;
    header.append(createPadding(length - header.length()));
    header.append("ALIVE");
    int aliveColumnLengh = 6;
    length += aliveColumnLengh;
    header.append(createPadding(length - header.length()));
    header.append("CPU TIME (SEC)");
    int cpuTimeColumnLengh = 14;
    length += cpuTimeColumnLengh;
    header.append(createPadding(length - header.length()));
    writer.println(header);

    int maxRowLength = header.length();

    writer.println(createPadding(maxRowLength, '-'));

    NumberFormat format = new DecimalFormat("0.#");

    for (ThreadStruct thread : threadList) {
        StringBuffer row = new StringBuffer();
        row.append(thread.ti.getThreadId());
        int rowLength = idColumnLength;
        row.append(createPadding(rowLength - row.length()));
        row.append(thread.getGroupName());
        rowLength += groupColumnLength;
        row.append(createPadding(rowLength - row.length()));
        row.append(thread.ti.getThreadName());
        rowLength += nameColumnLength;
        row.append(createPadding(rowLength - row.length()));
        row.append(thread.getPriority());
        rowLength += priorityColumnLength;
        row.append(createPadding(rowLength - row.length()));
        row.append(thread.ti.getThreadState());
        rowLength += stateColumnLength;
        row.append(createPadding(rowLength - row.length()));
        row.append(thread.isDaemon());
        rowLength += daemonColumnLengh;
        row.append(createPadding(rowLength - row.length()));
        row.append(thread.isAlive());
        rowLength += aliveColumnLengh;
        row.append(createPadding(rowLength - row.length()));
        double cpuTimeSec = (double) threadMxBean.getThreadCpuTime(thread.ti.getThreadId())
                / (double) (1000 * 1000 * 1000);
        row.append(format.format(cpuTimeSec));
        writer.println(row);
    }

    writer.println(createPadding(maxRowLength, '-'));
    writer.println("SUMMARY:");
    writer.println(createPadding(maxRowLength, '-'));

    for (State state : threadStatistics.keySet()) {
        int count = threadStatistics.get(state);
        if (count > 0) {
            StringBuffer row = new StringBuffer();
            row.append(state.toString());
            row.append(createPadding(stateColumnLength - row.length()));
            row.append(count);
            writer.println(row);
        }
    }
    writer.println(createPadding(maxRowLength, '-'));
    StringBuffer row = new StringBuffer();
    row.append("TOTAL");
    row.append(createPadding(stateColumnLength - row.length()));
    row.append(threadList.size());
    writer.println(row);
    writer.println(createPadding(maxRowLength, '-'));
}

From source file:net.centro.rtb.monitoringcenter.MonitoringCenterServlet.java

@Override
public void init(ServletConfig servletConfig) throws ServletException {
    super.init(servletConfig);

    boolean disableAuthorization = Boolean.TRUE.toString()
            .equalsIgnoreCase(servletConfig.getInitParameter(DISABLE_AUTHORIZATION_INIT_PARAM));
    if (!disableAuthorization) {
        String credentials = null;

        String username = servletConfig.getInitParameter(USERNAME_INIT_PARAM);
        String password = servletConfig.getInitParameter(PASSWORD_INIT_PARAM);
        if (StringUtils.isNotBlank(username) && StringUtils.isNotBlank(password)) {
            credentials = username.trim() + ":" + password.trim();
        } else {//from   w  w w. j  ava2 s . c o m
            credentials = DEFAULT_CREDENTIALS;
        }

        this.encodedCredentials = BaseEncoding.base64().encode(credentials.getBytes());
    }

    this.objectMapper = new ObjectMapper()
            .registerModule(new MetricsModule(TimeUnit.SECONDS, TimeUnit.MICROSECONDS, false))
            .registerModule(new HealthCheckModule()).setSerializationInclusion(JsonInclude.Include.NON_NULL)
            .setTimeZone(TimeZone.getDefault()).setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss z"));

    this.graphiteMetricFormatter = new GraphiteMetricFormatter(TimeUnit.SECONDS, TimeUnit.MICROSECONDS);

    try {
        this.threadDumpGenerator = new ThreadDump(ManagementFactory.getThreadMXBean());
    } catch (NoClassDefFoundError ignore) {
    }

    ServletContext servletContext = servletConfig.getServletContext();
    String servletSpecVersion = servletContext.getMajorVersion() + "." + servletContext.getMinorVersion();
    this.serverInfo = ServerInfo.create(servletContext.getServerInfo(), servletSpecVersion);
}

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  ava  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:net.bull.javamelody.internal.model.JavaInformations.java

public static List<ThreadInformations> buildThreadInformationsList() {
    final ThreadMXBean threadBean = ManagementFactory.getThreadMXBean();
    final Map<Thread, StackTraceElement[]> stackTraces = Thread.getAllStackTraces();
    final List<Thread> threads = new ArrayList<Thread>(stackTraces.keySet());

    // si "1.6.0_01".compareTo(Parameters.JAVA_VERSION) > 0;
    // on rcuprait les threads sans stack trace en contournant bug 6434648 avant 1.6.0_01
    // http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6434648
    // hormis pour le thread courant qui obtient sa stack trace diffremment sans le bug
    //      threads = getThreadsFromThreadGroups();
    //      final Thread currentThread = Thread.currentThread();
    //      stackTraces = Collections.singletonMap(currentThread, currentThread.getStackTrace());

    final boolean cpuTimeEnabled = threadBean.isThreadCpuTimeSupported() && threadBean.isThreadCpuTimeEnabled();
    final long[] deadlockedThreads = getDeadlockedThreads(threadBean);
    final List<ThreadInformations> threadInfosList = new ArrayList<ThreadInformations>(threads.size());
    // hostAddress rcupr ici car il peut y avoir plus de 20000 threads
    final String hostAddress = Parameters.getHostAddress();
    for (final Thread thread : threads) {
        final StackTraceElement[] stackTraceElements = stackTraces.get(thread);
        final List<StackTraceElement> stackTraceElementList = stackTraceElements == null ? null
                : new ArrayList<StackTraceElement>(Arrays.asList(stackTraceElements));
        final long cpuTimeMillis;
        final long userTimeMillis;
        if (cpuTimeEnabled) {
            cpuTimeMillis = threadBean.getThreadCpuTime(thread.getId()) / 1000000;
            userTimeMillis = threadBean.getThreadUserTime(thread.getId()) / 1000000;
        } else {//ww  w.  j  a va2  s.  c  o  m
            cpuTimeMillis = -1;
            userTimeMillis = -1;
        }
        final boolean deadlocked = deadlockedThreads != null
                && Arrays.binarySearch(deadlockedThreads, thread.getId()) >= 0;
        // stackTraceElementList est une ArrayList et non unmodifiableList pour lisibilit xml
        threadInfosList.add(new ThreadInformations(thread, stackTraceElementList, cpuTimeMillis, userTimeMillis,
                deadlocked, hostAddress));
    }
    // on retourne ArrayList et non unmodifiableList pour lisibilit du xml par xstream
    return threadInfosList;
}

From source file:com.alibaba.druid.benckmark.pool.PoolPerformanceTest.java

private void p0(final DataSource dataSource, String name, int threadCount) throws Exception {
    //ThreadUtils.doSleep(600000);
    final CountDownLatch startLatch = new CountDownLatch(1);
    final CountDownLatch endLatch = new CountDownLatch(threadCount);
    final CountDownLatch dumpLatch = new CountDownLatch(1);

    Thread[] threads = new Thread[threadCount];
    for (int i = 0; i < threadCount; ++i) {
        Thread thread = new Thread() {

            public void run() {
                try {
                    startLatch.await();//from   ww  w . j  a va2  s . c o m

                    for (int i = 0; i < LOOP_COUNT; ++i) {
                        Connection conn = dataSource.getConnection();
                        conn.close();
                    }
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
                endLatch.countDown();

                try {
                    dumpLatch.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        };
        threads[i] = thread;
        thread.start();
    }
    long startMillis = System.currentTimeMillis();
    long startYGC = TestUtil.getYoungGC();
    long startFullGC = TestUtil.getFullGC();
    startLatch.countDown();
    endLatch.await();

    long[] threadIdArray = new long[threads.length];
    for (int i = 0; i < threads.length; ++i) {
        threadIdArray[i] = threads[i].getId();
    }
    ThreadInfo[] threadInfoArray = ManagementFactory.getThreadMXBean().getThreadInfo(threadIdArray);
    dumpLatch.countDown();

    long blockedCount = 0;
    long waitedCount = 0;
    for (int i = 0; i < threadInfoArray.length; ++i) {
        ThreadInfo threadInfo = threadInfoArray[i];
        blockedCount += threadInfo.getBlockedCount();
        waitedCount += threadInfo.getWaitedCount();
    }

    long millis = System.currentTimeMillis() - startMillis;
    long ygc = TestUtil.getYoungGC() - startYGC;
    long fullGC = TestUtil.getFullGC() - startFullGC;
    System.out.println("thread " + threadCount + " " + name + " millis : "
            + NumberFormat.getInstance().format(millis) + "; YGC " + ygc + " FGC " + fullGC + " blocked "
            + NumberFormat.getInstance().format(blockedCount) //
            + " waited " + NumberFormat.getInstance().format(waitedCount) + " physicalConn "
            + physicalConnStat.get());

}