Example usage for java.lang.management GarbageCollectorMXBean getName

List of usage examples for java.lang.management GarbageCollectorMXBean getName

Introduction

In this page you can find the example usage for java.lang.management GarbageCollectorMXBean getName.

Prototype

public String getName();

Source Link

Document

Returns the name representing this memory manager.

Usage

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

private static void instantiateGarbageCollectorMetrics(MetricGroup metrics) {
    List<GarbageCollectorMXBean> garbageCollectors = ManagementFactory.getGarbageCollectorMXBeans();

    for (final GarbageCollectorMXBean garbageCollector : garbageCollectors) {
        MetricGroup gcGroup = metrics.addGroup(garbageCollector.getName());
        gcGroup.gauge("Count", new Gauge<Long>() {
            @Override//from   www. j a  va 2  s  .  c  om
            public Long getValue() {
                return garbageCollector.getCollectionCount();
            }
        });
        gcGroup.gauge("Time", new Gauge<Long>() {
            @Override
            public Long getValue() {
                return garbageCollector.getCollectionTime();
            }
        });
    }
}

From source file:com.buaa.cfs.utils.JvmPauseMonitor.java

private Map<String, GcTimes> getGcTimes() {
    Map<String, GcTimes> map = Maps.newHashMap();
    List<GarbageCollectorMXBean> gcBeans = ManagementFactory.getGarbageCollectorMXBeans();
    for (GarbageCollectorMXBean gcBean : gcBeans) {
        map.put(gcBean.getName(), new GcTimes(gcBean));
    }/*from   www. ja  va  2  s  .co m*/
    return map;
}

From source file:alluxio.util.JvmPauseMonitor.java

private Map<String, GarbageCollectorMXBean> getGarbageCollectorMXBeans() {
    List<GarbageCollectorMXBean> gcBeanList = ManagementFactory.getGarbageCollectorMXBeans();
    Map<String, GarbageCollectorMXBean> gcBeanMap = new HashMap();
    for (GarbageCollectorMXBean gcBean : gcBeanList) {
        gcBeanMap.put(gcBean.getName(), gcBean);
    }/*from   w  w w .  ja va  2 s .c o m*/
    return gcBeanMap;
}

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

/**
 * Add garbage collection metrics./*from  www .ja v a  2s .co m*/
 * 
 * @param result
 *            the result
 */
protected void addGarbageCollectionMetrics(Collection<Metric<?>> result) {
    List<GarbageCollectorMXBean> garbageCollectorMxBeans = ManagementFactory.getGarbageCollectorMXBeans();
    for (GarbageCollectorMXBean garbageCollectorMXBean : garbageCollectorMxBeans) {
        String name = beautifyGcName(garbageCollectorMXBean.getName());
        result.add(new Metric<Long>("gc." + name + ".count", garbageCollectorMXBean.getCollectionCount()));
        result.add(new Metric<Long>("gc." + name + ".time", garbageCollectorMXBean.getCollectionTime()));
    }
}

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

private void gcInfo(List<GarbageCollectorMXBean> garbageCollectorMXBeans, InformationStringBuilder builder) {
    builder.addSection("GC information");
    for (GarbageCollectorMXBean gcBean : garbageCollectorMXBeans) {
        builder.append(String.format("%s %s %s : %s (Count : Time)\n", gcBean.getName(),
                Arrays.toString(gcBean.getMemoryPoolNames()), gcBean.getCollectionCount(),
                gcBean.getCollectionTime()));
    }// ww  w.  jav a 2  s.  c  om
}

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   ww  w .j  a v  a  2  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:VerboseGC.java

/**
 * Prints the verbose GC log to System.out to list the memory usage of all
 * memory pools as well as the GC statistics.
 *///from ww w .j a v a 2  s  .  c om
public void printVerboseGc() {
    System.out.print("Uptime: " + formatMillis(rmbean.getUptime()));
    for (GarbageCollectorMXBean gc : gcmbeans) {
        System.out.print(" [" + gc.getName() + ": ");
        System.out.print("Count=" + gc.getCollectionCount());
        System.out.print(" GCTime=" + formatMillis(gc.getCollectionTime()));
        System.out.print("]");
    }
    System.out.println();
    for (MemoryPoolMXBean p : pools) {
        System.out.print("  [" + p.getName() + ":");
        MemoryUsage u = p.getUsage();
        System.out.print(" Used=" + formatBytes(u.getUsed()));
        System.out.print(" Committed=" + formatBytes(u.getCommitted()));
        System.out.println("]");
    }
}

From source file:org.apache.hama.monitor.plugin.JvmTask.java

private void gc(final MetricsRecord record) {
    long count = 0;
    long timeMillis = 0;
    for (GarbageCollectorMXBean gcBean : gcBeans) {
        long c = gcBean.getCollectionCount();
        long t = gcBean.getCollectionTime();
        String name = gcBean.getName();
        record.add(new Metric("GcCount" + name, c));
        record.add(new Metric("GcTimeMillis" + name, t));
        count += c;//from   ww w. jav a2  s . com
        timeMillis += t;
    }
    record.add(new Metric(GcCount, count));
    record.add(new Metric(GcTimeMillis, timeMillis));

    if (LOG.isDebugEnabled()) {
        LOG.debug(GcCount.description() + ": " + count);
        LOG.debug(GcTimeMillis.description() + ": " + timeMillis);
    }
}

From source file:alluxio.util.JvmPauseMonitor.java

private String formatLogString(long extraSleepTime, Map<String, GarbageCollectorMXBean> gcMXBeanMapBeforeSleep,
        Map<String, GarbageCollectorMXBean> gcMXBeanMapAfterSleep) {
    List<String> beanDiffs = Lists.newArrayList();
    GarbageCollectorMXBean oldBean;
    GarbageCollectorMXBean newBean;
    Set<String> nameSet = Sets.intersection(gcMXBeanMapBeforeSleep.keySet(), gcMXBeanMapAfterSleep.keySet());
    for (String name : nameSet) {
        oldBean = gcMXBeanMapBeforeSleep.get(name);
        newBean = gcMXBeanMapAfterSleep.get(name);
        if (oldBean == null) {
            beanDiffs.add("new GCBean created name= '" + newBean.getName() + " count="
                    + newBean.getCollectionCount() + " time=" + newBean.getCollectionTime() + "ms");
        } else if (newBean == null) {
            beanDiffs.add("old GCBean canceled name= '" + oldBean.getName() + " count="
                    + oldBean.getCollectionCount() + " time=" + oldBean.getCollectionTime() + "ms");
        } else {//w  w  w .j a  va 2 s.com
            if (oldBean.getCollectionTime() != newBean.getCollectionTime()
                    || oldBean.getCollectionCount() != newBean.getCollectionCount()) {
                beanDiffs.add("GC name= '" + newBean.getName() + " count=" + newBean.getCollectionCount()
                        + " time=" + newBean.getCollectionTime() + "ms");
            }
        }
    }
    StringBuilder ret = new StringBuilder().append("JVM paused ").append(extraSleepTime).append("ms\n");
    if (beanDiffs.isEmpty()) {
        ret.append("No GCs detected ");
    } else {
        ret.append("GC list:\n" + Joiner.on("\n").join(beanDiffs));
    }
    ret.append("\n").append(getMemoryInfo());
    return ret.toString();
}

From source file:org.jenkinsci.remoting.engine.HandlerLoopbackLoadStress.java

public HandlerLoopbackLoadStress(Config config)
        throws IOException, NoSuchAlgorithmException, CertificateException, KeyStoreException,
        UnrecoverableKeyException, KeyManagementException, OperatorCreationException {
    this.config = config;
    KeyPairGenerator gen = KeyPairGenerator.getInstance("RSA");
    gen.initialize(2048); // maximum supported by JVM with export restrictions
    keyPair = gen.generateKeyPair();/*w  ww  .ja  va  2s .c  om*/

    Date now = new Date();
    Date firstDate = new Date(now.getTime() + TimeUnit.DAYS.toMillis(10));
    Date lastDate = new Date(now.getTime() + TimeUnit.DAYS.toMillis(-10));

    SubjectPublicKeyInfo subjectPublicKeyInfo = SubjectPublicKeyInfo
            .getInstance(keyPair.getPublic().getEncoded());

    X500NameBuilder nameBuilder = new X500NameBuilder(BCStyle.INSTANCE);
    X500Name subject = nameBuilder.addRDN(BCStyle.CN, getClass().getSimpleName()).addRDN(BCStyle.C, "US")
            .build();

    X509v3CertificateBuilder certGen = new X509v3CertificateBuilder(subject, BigInteger.ONE, firstDate,
            lastDate, subject, subjectPublicKeyInfo);

    JcaX509ExtensionUtils instance = new JcaX509ExtensionUtils();

    certGen.addExtension(X509Extension.subjectKeyIdentifier, false,
            instance.createSubjectKeyIdentifier(subjectPublicKeyInfo));

    ContentSigner signer = new JcaContentSignerBuilder("SHA1withRSA").setProvider(BOUNCY_CASTLE_PROVIDER)
            .build(keyPair.getPrivate());

    certificate = new JcaX509CertificateConverter().setProvider(BOUNCY_CASTLE_PROVIDER)
            .getCertificate(certGen.build(signer));

    char[] password = "password".toCharArray();

    KeyStore store = KeyStore.getInstance("jks");
    store.load(null, password);
    store.setKeyEntry("alias", keyPair.getPrivate(), password, new Certificate[] { certificate });

    KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
    kmf.init(store, password);

    context = SSLContext.getInstance("TLS");
    context.init(kmf.getKeyManagers(), new TrustManager[] { new BlindTrustX509ExtendedTrustManager() }, null);

    mainHub = IOHub.create(executorService);
    // on windows there is a bug whereby you cannot mix ServerSockets and Sockets on the same selector
    acceptorHub = File.pathSeparatorChar == 59 ? IOHub.create(executorService) : mainHub;
    legacyHub = new NioChannelHub(executorService);
    executorService.submit(legacyHub);
    serverSocketChannel = ServerSocketChannel.open();

    JnlpProtocolHandler handler = null;
    for (JnlpProtocolHandler h : new JnlpProtocolHandlerFactory(executorService).withNioChannelHub(legacyHub)
            .withIOHub(mainHub).withSSLContext(context).withPreferNonBlockingIO(!config.bio)
            .withClientDatabase(new JnlpClientDatabase() {
                @Override
                public boolean exists(String clientName) {
                    return true;
                }

                @Override
                public String getSecretOf(@Nonnull String clientName) {
                    return secretFor(clientName);
                }
            }).withSSLClientAuthRequired(false).handlers()) {
        if (config.name.equals(h.getName())) {
            handler = h;
            break;
        }
    }
    if (handler == null) {
        throw new RuntimeException("Unknown handler: " + config.name);
    }
    this.handler = handler;

    acceptor = new Acceptor(serverSocketChannel);
    runtimeMXBean = ManagementFactory.getRuntimeMXBean();
    operatingSystemMXBean = ManagementFactory.getOperatingSystemMXBean();
    _getProcessCpuTime = _getProcessCpuTime(operatingSystemMXBean);
    garbageCollectorMXBeans = new ArrayList<GarbageCollectorMXBean>(
            ManagementFactory.getGarbageCollectorMXBeans());
    Collections.sort(garbageCollectorMXBeans, new Comparator<GarbageCollectorMXBean>() {
        @Override
        public int compare(GarbageCollectorMXBean o1, GarbageCollectorMXBean o2) {
            return o1.getName().compareTo(o2.getName());
        }
    });
    stats = new Stats();
}