Example usage for java.lang.management ThreadMXBean getPeakThreadCount

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

Introduction

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

Prototype

public int getPeakThreadCount();

Source Link

Document

Returns the peak live thread count since the Java virtual machine started or peak was reset.

Usage

From source file:MainClass.java

public static void premain(final Instrumentation inst) {
    Runtime.getRuntime().addShutdownHook(new Thread() {
        public void run() {
            try {
                PrintWriter out = new PrintWriter(System.err);

                ThreadMXBean tb = ManagementFactory.getThreadMXBean();
                out.printf("Current thread count: %d%n", tb.getThreadCount());
                out.printf("Peak thread count: %d%n", tb.getPeakThreadCount());

                List<MemoryPoolMXBean> pools = ManagementFactory.getMemoryPoolMXBeans();
                for (MemoryPoolMXBean pool : pools) {
                    MemoryUsage peak = pool.getPeakUsage();
                    out.printf("Peak %s memory used: %,d%n", pool.getName(), peak.getUsed());
                    out.printf("Peak %s memory reserved: %,d%n", pool.getName(), peak.getCommitted());
                }// w ww. j  av a2 s  .  co m

                Class[] loaded = inst.getAllLoadedClasses();
                out.println("Loaded classes:");
                for (Class c : loaded)
                    out.println(c.getName());
                out.close();
            } catch (Throwable t) {
                System.err.println("Exception in agent: " + t);
            }
        }
    });
}

From source file:ro.nextreports.server.web.debug.InfoUtil.java

public static List<Info> getGeneralJVMInfo() {
    List<Info> infos = new ArrayList<Info>();

    RuntimeMXBean runtimeBean = ManagementFactory.getRuntimeMXBean();
    infos.add(new Info("uptime", "" + Duration.milliseconds(runtimeBean.getUptime()).toString()));
    infos.add(new Info("name", runtimeBean.getName()));
    infos.add(new Info("pid", runtimeBean.getName().split("@")[0]));

    OperatingSystemMXBean systemBean = ManagementFactory.getOperatingSystemMXBean();
    infos.add(new Info("os name", "" + systemBean.getName()));
    infos.add(new Info("os version", "" + systemBean.getVersion()));
    infos.add(new Info("system load average", "" + systemBean.getSystemLoadAverage()));
    infos.add(new Info("available processors", "" + systemBean.getAvailableProcessors()));

    ThreadMXBean threadBean = ManagementFactory.getThreadMXBean();
    infos.add(new Info("thread count", "" + threadBean.getThreadCount()));
    infos.add(new Info("peak thread count", "" + threadBean.getPeakThreadCount()));

    MemoryMXBean memoryBean = ManagementFactory.getMemoryMXBean();
    infos.add(new Info("heap memory used",
            FileUtils.byteCountToDisplaySize(memoryBean.getHeapMemoryUsage().getUsed())));
    infos.add(new Info("non-heap memory used",
            FileUtils.byteCountToDisplaySize(memoryBean.getNonHeapMemoryUsage().getUsed())));

    return infos;
}

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

/**
 * @param clientPrixy/*www .j a  v a2  s .  c o  m*/
 * @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 getPeakThreadCount() {
    ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean();
    return threadMXBean.getPeakThreadCount();
}

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

/**
 * Add thread metrics./* www.  j ava  2s . com*/
 * 
 * @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: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 {//  www . j  av  a2s.  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.eclipse.gyrex.cloud.internal.NodeMetricsReporter.java

@Override
protected IStatus run(final IProgressMonitor monitor) {
    if (monitor.isCanceled()) {
        return Status.CANCEL_STATUS;
    }/*from   ww  w .ja  va 2s  . 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.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: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");
            }/* w  w w . j  a va  2 s  .c o  m*/
            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.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");
            }//w w  w. java2s .  co  m
            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");
    }
}