Example usage for java.lang.management ThreadMXBean getThreadCount

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

Introduction

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

Prototype

public int getThreadCount();

Source Link

Document

Returns the current number of live threads including both daemon and non-daemon threads.

Usage

From source file:org.apache.flink.runtime.metrics.util.MetricUtils.java

private static void instantiateThreadMetrics(MetricGroup metrics) {
    final ThreadMXBean mxBean = ManagementFactory.getThreadMXBean();

    metrics.gauge("Count", new Gauge<Integer>() {
        @Override//  w w w .j av a  2 s.  co  m
        public Integer getValue() {
            return mxBean.getThreadCount();
        }
    });
}

From source file:org.fluentd.jvmwatcher.data.JvmStateLog.java

/**
 * @param clientPrixy//from  ww  w  .  j a  va  2  s . c  om
 * @return
 */
public static JvmStateLog makeJvmStateLog(JvmClientProxy clientProxy) {
    JvmStateLog ret = new JvmStateLog();

    try {
        // set log time
        ret.logDateTime_ = System.currentTimeMillis();

        // ClassLoadingMXBean
        ClassLoadingMXBean classLoadingBean = clientProxy.getClassLoadingMXBean();
        if (null != classLoadingBean) {
            ret.classLoadedCount_ = classLoadingBean.getLoadedClassCount();
            ret.classUnloadedCount_ = classLoadingBean.getUnloadedClassCount();
            ret.classTotalLoadedCount_ = classLoadingBean.getTotalLoadedClassCount();
        }

        // CompilationMXBean
        CompilationMXBean compilationBean = clientProxy.getCompilationMXBean();
        if (null != compilationBean) {
            ret.compileTime_ = compilationBean.getTotalCompilationTime();
        }

        // MemoryMXBean
        MemoryMXBean memoryBean = clientProxy.getMemoryMXBean();
        if (null != memoryBean) {
            ret.heapSize_ = memoryBean.getHeapMemoryUsage();
            ret.notheapSize_ = memoryBean.getNonHeapMemoryUsage();
            ret.pendingFinalizationCount_ = memoryBean.getObjectPendingFinalizationCount();
        }

        // ThreadMXBean
        ThreadMXBean threadBean = clientProxy.getThreadMXBean();
        if (null != threadBean) {
            ret.threadCount_ = threadBean.getThreadCount();
            ret.daemonThreadCount_ = threadBean.getDaemonThreadCount();
            ret.peakThreadCount_ = threadBean.getPeakThreadCount();
        }

        // OperatingSystemMXBean
        OperatingSystemMXBean OpeSysBean = clientProxy.getOperatingSystemMXBean();
        if (null != OpeSysBean) {
            ret.osAvailableProcessors_ = OpeSysBean.getAvailableProcessors();
            ret.osSystemLoadAverage_ = OpeSysBean.getSystemLoadAverage();
        }

        // com.sun.management.OperatingSystemMXBean
        com.sun.management.OperatingSystemMXBean sunOpeSysBean = clientProxy.getSunOperatingSystemMXBean();
        if (null != sunOpeSysBean) {
            ret.committedVirtualMemorySize_ = sunOpeSysBean.getCommittedVirtualMemorySize();
            ret.freePhysicalMemorySize_ = sunOpeSysBean.getFreePhysicalMemorySize();
            ret.freeSwapSpaceSize_ = sunOpeSysBean.getFreeSwapSpaceSize();
            ret.processCpuTime_ = sunOpeSysBean.getProcessCpuTime();
            ret.totalPhysicalMemorySize_ = sunOpeSysBean.getTotalPhysicalMemorySize();
            ret.totalSwapSpaceSize_ = sunOpeSysBean.getTotalSwapSpaceSize();
        }

        // RuntimeMXBean
        RuntimeMXBean runtimeBean = clientProxy.getRuntimeMXBean();
        if (null != runtimeBean) {
            ret.jvmUpTime_ = runtimeBean.getUptime();
        }

        // MemoryPoolMXBean
        Collection<MemoryPoolClientProxy> memoryPoolBeansColl = clientProxy.getMemoryPoolClientProxies();
        if (null != memoryPoolBeansColl) {
            ret.memoryPoolStateColl_ = new ArrayList<MemoryPoolState>();
            for (MemoryPoolClientProxy elem : memoryPoolBeansColl) {
                if (null != elem) {
                    MemoryPoolState state = elem.getStat();
                    if (null != state) {
                        // add MemoryPoolState
                        ret.memoryPoolStateColl_.add(state);
                    }
                }
            }
        }

        // GarbageCollectorMXBean
        Collection<GarbageCollectorMXBean> garbageCollBeansColl = clientProxy.getGarbageCollectorMXBeans();
        if (null != garbageCollBeansColl) {
            ret.gcCollectorState_ = new ArrayList<GarbageCollectorState>();
            for (GarbageCollectorMXBean elem : garbageCollBeansColl) {
                if (null != elem) {
                    long collectionCount = elem.getCollectionCount();
                    long collectionTime = elem.getCollectionTime();
                    String memoryManagerName = elem.getName();
                    GarbageCollectorState state = new GarbageCollectorState(memoryManagerName, collectionCount,
                            collectionTime);
                    // add GarbageCollectorState
                    ret.gcCollectorState_.add(state);
                }
            }
        }
    } catch (IOException ex) {
        log.error(ex);
        // close JvmClientProxy
        clientProxy.disconnect();
    } catch (Exception ex) {
        log.error(ex);
        // close JvmClientProxy
        clientProxy.disconnect();
    }

    return ret;
}

From source file:com.amazonaws.client.metrics.support.JmxInfoProviderSupport.java

@Override
public int getThreadCount() {
    ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean();
    return threadMXBean.getThreadCount();
}

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

private Map<String, Object> getThreadCount(ThreadMXBean threadMXBean) {
    LinkedHashMap<String, Object> count = new LinkedHashMap<>();
    count.put("Current", threadMXBean.getThreadCount());
    count.put("Total", threadMXBean.getTotalStartedThreadCount());
    count.put("Daemon", threadMXBean.getDaemonThreadCount());
    count.put("Peak", threadMXBean.getPeakThreadCount());
    return count;
}

From source file:org.eclipse.gyrex.cloud.internal.NodeMetricsReporter.java

@Override
protected IStatus run(final IProgressMonitor monitor) {
    if (monitor.isCanceled()) {
        return Status.CANCEL_STATUS;
    }/* ww w  . j  av a 2 s .c o  m*/

    try {
        final Properties metrics = new Properties() {
            private static final long serialVersionUID = 1L;

            @Override
            public synchronized Enumeration<Object> keys() {
                return Collections.enumeration(keySet());
            }

            @Override
            public Set<Object> keySet() {
                return new TreeSet<Object>(super.keySet());
            }
        };
        final OperatingSystemMXBean operatingSystemMXBean = ManagementFactory.getOperatingSystemMXBean();
        metrics.setProperty("os.availableProcessors",
                String.valueOf(operatingSystemMXBean.getAvailableProcessors()));
        metrics.setProperty("os.systemLoadAverage",
                String.valueOf(operatingSystemMXBean.getSystemLoadAverage()));
        metrics.setProperty("os.committedVirtualMemorySize",
                getUsingReflection(operatingSystemMXBean, "getCommittedVirtualMemorySize"));
        metrics.setProperty("os.totalSwapSpaceSize",
                getUsingReflection(operatingSystemMXBean, "getTotalSwapSpaceSize"));
        metrics.setProperty("os.freeSwapSpaceSize",
                getUsingReflection(operatingSystemMXBean, "getFreeSwapSpaceSize"));
        metrics.setProperty("os.processCpuTime",
                getUsingReflection(operatingSystemMXBean, "getProcessCpuTime"));
        metrics.setProperty("os.freePhysicalMemorySize",
                getUsingReflection(operatingSystemMXBean, "getFreePhysicalMemorySize"));
        metrics.setProperty("os.totalPhysicalMemorySize",
                getUsingReflection(operatingSystemMXBean, "getTotalPhysicalMemorySize"));
        metrics.setProperty("os.openFileDescriptorCount",
                getUsingReflection(operatingSystemMXBean, "getOpenFileDescriptorCount"));
        metrics.setProperty("os.maxFileDescriptorCount",
                getUsingReflection(operatingSystemMXBean, "getMaxFileDescriptorCount"));

        final MemoryMXBean memoryMXBean = ManagementFactory.getMemoryMXBean();
        final MemoryUsage heapMemoryUsage = memoryMXBean.getHeapMemoryUsage();
        metrics.setProperty("heap.used", String.valueOf(heapMemoryUsage.getUsed()));
        metrics.setProperty("heap.committed", String.valueOf(heapMemoryUsage.getCommitted()));
        metrics.setProperty("heap.max", String.valueOf(heapMemoryUsage.getMax()));
        metrics.setProperty("heap.init", String.valueOf(heapMemoryUsage.getInit()));
        final MemoryUsage nonHeapMemoryUsage = memoryMXBean.getNonHeapMemoryUsage();
        metrics.setProperty("nonHeap.used", String.valueOf(nonHeapMemoryUsage.getUsed()));
        metrics.setProperty("nonHeap.committed", String.valueOf(nonHeapMemoryUsage.getCommitted()));
        metrics.setProperty("nonHeap.max", String.valueOf(nonHeapMemoryUsage.getMax()));
        metrics.setProperty("nonHeap.init", String.valueOf(nonHeapMemoryUsage.getInit()));

        final ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean();
        metrics.setProperty("thread.count", String.valueOf(threadMXBean.getThreadCount()));
        metrics.setProperty("thread.peak", String.valueOf(threadMXBean.getPeakThreadCount()));
        metrics.setProperty("thread.totalStarted", String.valueOf(threadMXBean.getTotalStartedThreadCount()));

        final RuntimeMXBean runtimeMXBean = ManagementFactory.getRuntimeMXBean();
        metrics.setProperty("uptime", String.valueOf(runtimeMXBean.getUptime()));

        final ByteArrayOutputStream out = new ByteArrayOutputStream();
        final NodeInfo nodeInfo = CloudState.getNodeInfo();
        metrics.store(out, String.valueOf(nodeInfo));
        ZooKeeperGate.get().writeRecord(IZooKeeperLayout.PATH_NODES_METRICS.append(nodeInfo.getNodeId()),
                CreateMode.PERSISTENT, out.toByteArray());
        if (CloudDebug.nodeMetrics) {
            LOG.debug("Node metrics reported successfully.{}{}", SystemUtils.LINE_SEPARATOR,
                    new String(out.toByteArray(), CharEncoding.ISO_8859_1));
        }
    } catch (final Exception e) {
        LOG.warn("Failed to update node metrics. {}", e.getMessage());
    } finally {
        // reschedule
        schedule(DELAY);
    }

    return Status.OK_STATUS;
}

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

private void threadInfo(ThreadMXBean threadMXBean, InformationStringBuilder builder) {
    builder.addSection("Thread information");

    builder.append(String.format("Current: %s, Total: %s, Daemon: %s, Peak: %s\n",
            threadMXBean.getThreadCount(), threadMXBean.getTotalStartedThreadCount(),
            threadMXBean.getDaemonThreadCount(), threadMXBean.getPeakThreadCount()));
    long[] deadlockedThreads = threadMXBean.findDeadlockedThreads();
    if (deadlockedThreads != null && deadlockedThreads.length > 0) {
        builder.append(String.format("Found %s dead locked threads. Here is there information.\n",
                deadlockedThreads.length));
        for (long deadlockedThread : deadlockedThreads) {
            ThreadInfo threadInfo = threadMXBean.getThreadInfo(deadlockedThread);
            LockInfo lockInfo = threadInfo.getLockInfo();
            if (lockInfo != null) {
                builder.append(String.format("LockInfo: %s", lockInfo));
            } else {
                builder.append("This thread is not waiting for any locks\n");
            }//from w  w  w .j  a  v a2 s.  c  om
            builder.append(String.format("Monitor Info - Stack Frame where locks were taken.\n"));
            MonitorInfo[] lockedMonitors = threadInfo.getLockedMonitors();
            for (MonitorInfo lockedMonitor : lockedMonitors) {
                builder.append(String.format("Monitor for class '%s' taken at stack frame '%s'.",
                        lockedMonitor.getClassName(), lockedMonitor.getLockedStackFrame()));
            }
            builder.append("The stack trace of the deadlocked thread\n");
            builder.append(Arrays.toString(threadInfo.getStackTrace()));
        }
    }
    builder.addSubSection("All thread stacktraces");
    ThreadInfo[] threadInfos = threadMXBean.dumpAllThreads(true, true);
    for (ThreadInfo threadInfo : threadInfos) {
        builder.append(String.format("%s, %s, %s\n", threadInfo.getThreadId(), threadInfo.getThreadName(),
                threadInfo.getThreadState()));
        MonitorInfo[] lockedMonitors = threadInfo.getLockedMonitors();
        builder.append("Locked Monitors:\n");
        for (MonitorInfo lockedMonitor : lockedMonitors) {
            builder.append(String.format("%s at %s", lockedMonitor, lockedMonitor.getLockedStackFrame()));
        }
        LockInfo[] lockedSynchronizers = threadInfo.getLockedSynchronizers();
        builder.append("Locked Synchronizers:\n");
        for (LockInfo lockedSynchronizer : lockedSynchronizers) {
            builder.append(lockedSynchronizer);
        }
        builder.append("Stacktrace:\n  ");
        builder.append(StringUtils.join(threadInfo.getStackTrace(), "\n  "));
        builder.append("\n\n");
    }
}

From source file:com.snowstore.mercury.core.metric.SystemPublicMetrics.java

/**
 * Add thread metrics.//from   w w w . j  a v a2  s.  c  om
 * 
 * @param result
 *            the result
 */
protected void addThreadMetrics(Collection<Metric<?>> result) {
    ThreadMXBean threadMxBean = ManagementFactory.getThreadMXBean();
    result.add(new Metric<Long>("threads.peak", (long) threadMxBean.getPeakThreadCount()));
    result.add(new Metric<Long>("threads.daemon", (long) threadMxBean.getDaemonThreadCount()));
    result.add(new Metric<Long>("threads", (long) threadMxBean.getThreadCount()));
}

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

@Override
public void appendInformation(InformationStringBuilder builder) {
    ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean();
    builder.addSection("Thread information");

    builder.append(String.format("Current: %s, Total: %s, Daemon: %s, Peak: %s\n",
            threadMXBean.getThreadCount(), threadMXBean.getTotalStartedThreadCount(),
            threadMXBean.getDaemonThreadCount(), threadMXBean.getPeakThreadCount()));
    long[] deadlockedThreads = threadMXBean.findDeadlockedThreads();
    if (deadlockedThreads != null && deadlockedThreads.length > 0) {
        builder.append(String.format("Found %s dead locked threads. Here is there information.\n",
                deadlockedThreads.length));
        for (long deadlockedThread : deadlockedThreads) {
            ThreadInfo threadInfo = threadMXBean.getThreadInfo(deadlockedThread);
            LockInfo lockInfo = threadInfo.getLockInfo();
            if (lockInfo != null) {
                builder.append(String.format("LockInfo: %s", lockInfo));
            } else {
                builder.append("This thread is not waiting for any locks\n");
            }//from  ww  w  .  j  ava  2s .c om
            builder.append(String.format("Monitor Info - Stack Frame where locks were taken.\n"));
            MonitorInfo[] lockedMonitors = threadInfo.getLockedMonitors();
            for (MonitorInfo lockedMonitor : lockedMonitors) {
                builder.append(String.format("Monitor for class '%s' taken at stack frame '%s'.",
                        lockedMonitor.getClassName(), lockedMonitor.getLockedStackFrame()));
            }
            builder.append("The stack trace of the deadlocked thread\n");
            builder.append(Arrays.toString(threadInfo.getStackTrace()));
        }
    }
    builder.addSubSection("All thread stacktraces");
    ThreadInfo[] threadInfos = threadMXBean.dumpAllThreads(true, true);
    for (ThreadInfo threadInfo : threadInfos) {
        builder.append(String.format("%s, %s, %s\n", threadInfo.getThreadId(), threadInfo.getThreadName(),
                threadInfo.getThreadState()));
        MonitorInfo[] lockedMonitors = threadInfo.getLockedMonitors();
        builder.append("Locked Monitors:\n");
        for (MonitorInfo lockedMonitor : lockedMonitors) {
            builder.append(String.format("%s at %s", lockedMonitor, lockedMonitor.getLockedStackFrame()));
        }
        LockInfo[] lockedSynchronizers = threadInfo.getLockedSynchronizers();
        builder.append("Locked Synchronizers:\n");
        for (LockInfo lockedSynchronizer : lockedSynchronizers) {
            builder.append(lockedSynchronizer);
        }
        builder.append("Stacktrace:\n  ");
        builder.append(StringUtils.join(threadInfo.getStackTrace(), "\n  "));
        builder.append("\n\n");
    }
}

From source file:ca.simplegames.micro.controllers.StatsController.java

public void execute(MicroContext context, Map configuration) throws ControllerException {
    Map<String, Object> systemInfo = new HashMap<String, Object>();
    Map<String, Object> osMap = new HashMap<String, Object>();
    MBeanServerConnection mbeanServer = ManagementFactory.getPlatformMBeanServer();

    OperatingSystemMXBean sunOperatingSystemMXBean = null;
    try {/*from   www . j a v  a2 s  .c o m*/
        sunOperatingSystemMXBean = ManagementFactory.newPlatformMXBeanProxy(mbeanServer,
                ManagementFactory.OPERATING_SYSTEM_MXBEAN_NAME, OperatingSystemMXBean.class);
    } catch (IOException e) {
        throw new ControllerException(e.getMessage());
    }

    Runtime rt = Runtime.getRuntime();
    long totalMemory = rt.totalMemory() / MEGA_BYTE;
    long freeMemory = rt.freeMemory() / MEGA_BYTE;
    long usedMemory = totalMemory - freeMemory;

    final long p100 = (int) Math.round(((double) freeMemory / (double) totalMemory) * 100);

    Map<String, Long> memInfo = new HashMap<String, Long>();

    memInfo.put("total", totalMemory);
    memInfo.put("used", usedMemory);
    memInfo.put("free", freeMemory);
    memInfo.put("percent_free", p100);

    systemInfo.put("memory", memInfo);
    systemInfo.put("powered_by", POWERED_BY_MICRO);

    //cpu usage in milli secs
    long currentCpuUsage = sunOperatingSystemMXBean.getProcessCpuTime() / 1000000;
    osMap.put("cpu_usage", currentCpuUsage);
    osMap.put("available_processors", sunOperatingSystemMXBean.getAvailableProcessors());
    osMap.put("system_load_average", sunOperatingSystemMXBean.getSystemLoadAverage());
    osMap.put("committed_virtual_memory_size", sunOperatingSystemMXBean.getCommittedVirtualMemorySize());
    osMap.put("free_physical_memory_size", sunOperatingSystemMXBean.getFreePhysicalMemorySize());
    osMap.put("total_physical_memory_size", sunOperatingSystemMXBean.getTotalPhysicalMemorySize());
    osMap.put("free_swap_space_size", sunOperatingSystemMXBean.getFreeSwapSpaceSize());
    osMap.put("total_swap_space_size", sunOperatingSystemMXBean.getTotalSwapSpaceSize());

    systemInfo.put("os", osMap);

    List<GarbageCollectorMXBean> gc = ManagementFactory.getGarbageCollectorMXBeans();
    List<Map> gcInfo = new ArrayList<Map>();

    for (GarbageCollectorMXBean aGc : gc) {
        Map<String, Object> gcMap = new HashMap<String, Object>();
        gcMap.put("name", aGc.getName());
        gcMap.put("collection_count", aGc.getCollectionCount());
        gcMap.put("collection_time", aGc.getCollectionTime());

        gcInfo.add(gcMap);
    }

    systemInfo.put("gc", gcInfo);

    ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean();
    Map<String, Object> threadInfoMap = new HashMap<String, Object>(); // more to come ;)
    threadInfoMap.put("peak_thread_count", threadMXBean.getPeakThreadCount());
    threadInfoMap.put("thread_count", threadMXBean.getThreadCount());
    threadInfoMap.put("total_started_thread_count", threadMXBean.getTotalStartedThreadCount());

    long[] deadlockedThreads = threadMXBean.findMonitorDeadlockedThreads();
    threadInfoMap.put("dead_locked_thread_count", deadlockedThreads != null ? deadlockedThreads.length : 0);
    systemInfo.put("thread_info", threadInfoMap);

    JSONObject sysinfoJson = new JSONObject(Collections.singletonMap("system_info", systemInfo));

    String sysinfoString = null;
    try {
        sysinfoString = context.getRequest().getParameter("pretty") != null ? sysinfoJson.toString(2)
                : sysinfoJson.toString();
    } catch (JSONException e) {
        e.printStackTrace();
        throw new ControllerException(e.getMessage());
    }

    context.getRackResponse().withContentType(Mime.mimeType(JSON_TYPE)).withBody(sysinfoString)
            .withContentLength(sysinfoString.length()).with(Rack.MESSAGE_STATUS, HttpServletResponse.SC_OK);

    context.halt();
}

From source file:org.cloudfoundry.identity.statsd.UaaMetricsEmitter.java

@Scheduled(fixedRate = 5000, initialDelay = 3000)
public void emitJvmVitals() {
    OperatingSystemMXBean osBean = ManagementFactory.getOperatingSystemMXBean();
    ThreadMXBean threadBean = ManagementFactory.getThreadMXBean();
    MemoryMXBean memoryBean = ManagementFactory.getMemoryMXBean();
    String prefix = "vitals.jvm.";
    invokeIfPresent(prefix + "cpu.load", osBean, "getProcessCpuLoad", d -> (long) (d.doubleValue() * 100));
    statsDClient.gauge(prefix + "thread.count", threadBean.getThreadCount());
    Map<String, MemoryUsage> memory = new HashMap<>();
    memory.put("heap", memoryBean.getHeapMemoryUsage());
    memory.put("non-heap", memoryBean.getNonHeapMemoryUsage());
    memory.entrySet().stream().forEach(m -> {
        statsDClient.gauge(prefix + m.getKey() + ".init", m.getValue().getInit());
        statsDClient.gauge(prefix + m.getKey() + ".committed", m.getValue().getCommitted());
        statsDClient.gauge(prefix + m.getKey() + ".used", m.getValue().getUsed());
        statsDClient.gauge(prefix + m.getKey() + ".max", m.getValue().getMax());
    });//  w  ww  .ja v a 2  s  . com

}