Example usage for java.lang.management ManagementFactory getGarbageCollectorMXBeans

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

Introduction

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

Prototype

public static List<GarbageCollectorMXBean> getGarbageCollectorMXBeans() 

Source Link

Document

Returns a list of GarbageCollectorMXBean objects in the Java virtual machine.

Usage

From source file:org.commoncrawl.util.JVMStats.java

public static void dumpMemoryStats() {

    MemoryMXBean memoryMXBean = ManagementFactory.getMemoryMXBean();
    MemoryUsage memHeap = memoryMXBean.getHeapMemoryUsage();

    List<GarbageCollectorMXBean> gcBeans = ManagementFactory.getGarbageCollectorMXBeans();

    long gcTime = 0;
    for (GarbageCollectorMXBean gcBean : gcBeans) {
        gcTime += gcBean.getCollectionTime();
    }/*from   w  ww. j  a  va 2  s .co m*/

    float utilizationRatio = ((float) memHeap.getUsed()) / ((float) memHeap.getMax());

    LOG.info("Heap Size:" + memHeap.getUsed() / MBytes + " (MB) CommitSize:" + memHeap.getCommitted() / MBytes
            + " (MB) Max:" + memHeap.getMax() + " Ratio:" + utilizationRatio + " GCTime:"
            + (gcTime - lastGCTime) + "PendingFinalCnt:" + memoryMXBean.getObjectPendingFinalizationCount());

    lastGCTime = gcTime;
}

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

@Override
public void appendInformation(InformationStringBuilder infoCollector) {
    osInfo(ManagementFactory.getOperatingSystemMXBean(), infoCollector);
    runtimeInfo(ManagementFactory.getRuntimeMXBean(), infoCollector);
    gcInfo(ManagementFactory.getGarbageCollectorMXBeans(), infoCollector);
    memoryInfo(ManagementFactory.getMemoryMXBean(), infoCollector);
    poolInfo(infoCollector);//from  w  w w .jav  a2s  .co  m
    threadInfo(ManagementFactory.getThreadMXBean(), infoCollector);
}

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 . java 2 s .  com
            public Long getValue() {
                return garbageCollector.getCollectionCount();
            }
        });
        gcGroup.gauge("Time", new Gauge<Long>() {
            @Override
            public Long getValue() {
                return garbageCollector.getCollectionTime();
            }
        });
    }
}

From source file:org.teiid.sizing.Main.java

public static long collectionCount() {
    long totalGarbageCollections = 0;

    for (GarbageCollectorMXBean gc : ManagementFactory.getGarbageCollectorMXBeans()) {
        long count = gc.getCollectionCount();
        if (count >= 0) {
            totalGarbageCollections += count;
        }/*from ww  w .j  av  a  2  s .com*/
    }
    return totalGarbageCollections;
}

From source file:net.centro.rtb.monitoringcenter.metrics.system.jvm.GarbageCollectorMetricSet.java

GarbageCollectorMetricSet() {
    this.garbageCollectorMXBeans = ManagementFactory.getGarbageCollectorMXBeans();

    this.minorGcTimer = new Timer();
    this.majorGcTimer = new Timer();

    // Determine the location of the gc log file (note that there's not support for rolling gc logs)
    String gcLogFilePath = null;/*from   ww w.ja v a 2 s . c  o  m*/
    RuntimeMXBean runtimeMXBean = ManagementFactory.getRuntimeMXBean();
    List<String> inputArguments = runtimeMXBean.getInputArguments();
    for (String argument : inputArguments) {
        if (argument.startsWith(LOG_GC_JVM_PARAM)) {
            gcLogFilePath = argument.substring(LOG_GC_JVM_PARAM.length());
            break;
        }
    }

    if (gcLogFilePath != null && !gcLogFilePath.trim().isEmpty()) {
        final File gcLogFile = new File(gcLogFilePath);
        if (gcLogFile.exists()) {
            this.fullCollectionsCounter = new AtomicLong();

            this.gcLogTailer = Tailer.create(gcLogFile, new TailerListenerAdapter() {
                @Override
                public void handle(String line) {
                    if (line != null && line.contains(FULL_GC_LOG_STRING)) {
                        fullCollectionsCounter.incrementAndGet();
                    }
                }
            }, GC_LOG_FILE_TAIL_DELAY_IN_MILLIS);
        }
    }

    // Attach a listener to the GarbageCollectorMXBeans
    this.gcEventListener = new NotificationListener() {
        @Override
        public void handleNotification(Notification notification, Object handback) {
            String notificationType = notification.getType();
            if (notificationType.equals(GarbageCollectionNotificationInfo.GARBAGE_COLLECTION_NOTIFICATION)) {
                CompositeData compositeData = CompositeData.class.cast(notification.getUserData());
                GarbageCollectionNotificationInfo gcNotificationInfo = GarbageCollectionNotificationInfo
                        .from(compositeData);

                if (GC_NOTIFICATION_MINOR_GC_ACTION_STRING.equals(gcNotificationInfo.getGcAction())) {
                    minorGcTimer.update(gcNotificationInfo.getGcInfo().getDuration(), TimeUnit.MILLISECONDS);
                } else if (GC_NOTIFICATION_MAJOR_GC_ACTION_STRING.equals(gcNotificationInfo.getGcAction())) {
                    majorGcTimer.update(gcNotificationInfo.getGcInfo().getDuration(), TimeUnit.MILLISECONDS);
                }
            }
        }
    };

    for (final GarbageCollectorMXBean garbageCollectorMXBean : garbageCollectorMXBeans) {
        if (NotificationEmitter.class.isInstance(garbageCollectorMXBean)) {
            NotificationEmitter emitter = NotificationEmitter.class.cast(garbageCollectorMXBean);
            emitter.addNotificationListener(gcEventListener, null, null);
        }
    }

    // Set up metrics
    Map<String, Metric> metricsByNames = new HashMap<>();

    if (fullCollectionsCounter != null) {
        this.fullCollectionsGauge = new Gauge<Long>() {
            @Override
            public Long getValue() {
                return fullCollectionsCounter.get();
            }
        };
        metricsByNames.put("fullCollections", fullCollectionsGauge);
    }

    metricsByNames.put("majorGcTimer", majorGcTimer);
    metricsByNames.put("minorGcTimer", minorGcTimer);

    List<GarbageCollectorStatus> garbageCollectorStatuses = new ArrayList<>();
    for (final GarbageCollectorMXBean garbageCollectorMXBean : garbageCollectorMXBeans) {
        final String garbageCollectorName = garbageCollectorMXBean.getName();
        final String garbageCollectorNamespace = MetricNamingUtil.join("collectors",
                MetricNamingUtil.sanitize(garbageCollectorName));

        final Gauge<Long> collectionsGauge;
        if (garbageCollectorMXBean.getCollectionCount() >= 0) {
            collectionsGauge = new Gauge<Long>() {
                @Override
                public Long getValue() {
                    return garbageCollectorMXBean.getCollectionCount();
                }
            };
            metricsByNames.put(MetricNamingUtil.join(garbageCollectorNamespace, "collections"),
                    collectionsGauge);
        } else {
            collectionsGauge = null;
        }

        final Gauge<Long> totalCollectionDurationInMillisGauge;
        if (garbageCollectorMXBean.getCollectionTime() >= 0) {
            totalCollectionDurationInMillisGauge = new Gauge<Long>() {
                @Override
                public Long getValue() {
                    return garbageCollectorMXBean.getCollectionTime();
                }
            };
            metricsByNames.put(
                    MetricNamingUtil.join(garbageCollectorNamespace, "totalCollectionDurationInMillis"),
                    totalCollectionDurationInMillisGauge);
        } else {
            totalCollectionDurationInMillisGauge = null;
        }

        garbageCollectorStatuses.add(new GarbageCollectorStatus() {
            @Override
            public String getName() {
                return garbageCollectorName;
            }

            @Override
            public Gauge<Long> getCollectionsGauge() {
                return collectionsGauge;
            }

            @Override
            public Gauge<Long> getTotalCollectionDurationInMillisGauge() {
                return totalCollectionDurationInMillisGauge;
            }
        });
    }
    this.garbageCollectorStatuses = garbageCollectorStatuses;

    this.metricsByNames = metricsByNames;
}

From source file:org.teiid.sizing.Main.java

public static long collectionTimes() {
    long garbageCollectionTime = 0;

    for (GarbageCollectorMXBean gc : ManagementFactory.getGarbageCollectorMXBeans()) {
        long time = gc.getCollectionTime();
        if (time >= 0) {
            garbageCollectionTime += time;
        }/*from   ww  w  .j  a va  2s.  co  m*/
    }
    return garbageCollectionTime;
}

From source file:org.jboss.resteasy.test.response.ResponseStreamPrematurelyClosedTest.java

@Test
public void testStream() throws Exception {
    Builder builder = client.target(generateURL("/test/document/abc/content")).request();

    try (MyByteArrayOutputStream baos = new MyByteArrayOutputStream()) {

        if (!TestUtil.isIbmJdk()) {
            //builder.get().readEntity explicitly on the same line below and not saved in any temp variable
            //to let the JVM try finalizing the ClientResponse object
            InputStream ins = builder.get().readEntity(InputStream.class);
            //suggest jvm to do gc and wait the gc notification
            final CountDownLatch coutDown = new CountDownLatch(1);

            List<GarbageCollectorMXBean> gcbeans = ManagementFactory.getGarbageCollectorMXBeans();
            NotificationListener listener = new NotificationListener() {
                public void handleNotification(Notification notification, Object handback) {
                    coutDown.countDown();
                }/*from   www.jav a2  s . c  o  m*/
            };
            try {
                for (GarbageCollectorMXBean gcbean : gcbeans) {
                    NotificationEmitter emitter = (NotificationEmitter) gcbean;
                    emitter.addNotificationListener(listener, null, null);
                }
                System.gc();
                coutDown.await(10, TimeUnit.SECONDS);

                IOUtils.copy(ins, baos);
                Assert.assertEquals("Received string: " + baos.toShortString(), 10000000, baos.size());
            } finally {
                //remove the listener
                for (GarbageCollectorMXBean gcbean : gcbeans) {
                    ((NotificationEmitter) gcbean).removeNotificationListener(listener);
                }
            }
        } else { // workaround for Ibm jdk - doesn't allow to use NotificationEmitter with GarbageCollectorMXBean
            //builder.get().readEntity explicitly on the same line below and not saved in any temp variable
            //to let the JVM try finalizing the ClientResponse object
            IOUtils.copy(builder.get().readEntity(InputStream.class), baos);
            Assert.assertEquals(100000000, baos.size());
        }
    }
}

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 {// w  w  w .  j a  va2s. 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:edu.usu.sdl.openstorefront.web.rest.service.Application.java

@GET
@RequireAdmin/*from   ww  w.  j  a v  a2  s  .c o m*/
@APIDescription("Gets the application system status")
@Produces({ MediaType.APPLICATION_JSON })
@DataType(ApplicationStatus.class)
@Path("/status")
public Response getApplicationStatus() {
    OperatingSystemMXBean operatingSystemMXBean = ManagementFactory.getOperatingSystemMXBean();
    RuntimeMXBean runtimeMXBean = ManagementFactory.getRuntimeMXBean();
    List<GarbageCollectorMXBean> garbageCollectorMXBeans = ManagementFactory.getGarbageCollectorMXBeans();
    MemoryMXBean memoryMXBean = ManagementFactory.getMemoryMXBean();
    List<MemoryPoolMXBean> memoryPoolMXBeans = ManagementFactory.getMemoryPoolMXBeans();
    ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean();

    ApplicationStatus applicationStatus = new ApplicationStatus();
    applicationStatus.setApplicationVersion(PropertiesManager.getApplicationVersion());
    applicationStatus.setProcessorCount(operatingSystemMXBean.getAvailableProcessors());
    applicationStatus.setSystemLoad(operatingSystemMXBean.getSystemLoadAverage());
    applicationStatus.setSystemProperties(runtimeMXBean.getSystemProperties());

    applicationStatus.getHeapMemoryStatus().setName("Heap");
    applicationStatus.getHeapMemoryStatus().setDetails(memoryMXBean.getHeapMemoryUsage().toString());
    applicationStatus.getHeapMemoryStatus()
            .setInitKb(memoryMXBean.getHeapMemoryUsage().getInit() != 0
                    ? memoryMXBean.getHeapMemoryUsage().getInit() / 1024
                    : 0);
    applicationStatus.getHeapMemoryStatus()
            .setUsedKb(memoryMXBean.getHeapMemoryUsage().getUsed() != 0
                    ? memoryMXBean.getHeapMemoryUsage().getUsed() / 1024
                    : 0);
    applicationStatus.getHeapMemoryStatus()
            .setMaxKb(memoryMXBean.getHeapMemoryUsage().getMax() != 0
                    ? memoryMXBean.getHeapMemoryUsage().getMax() / 1024
                    : 0);
    applicationStatus.getHeapMemoryStatus()
            .setCommitedKb(memoryMXBean.getHeapMemoryUsage().getCommitted() != 0
                    ? memoryMXBean.getHeapMemoryUsage().getCommitted() / 1024
                    : 0);

    applicationStatus.getNonHeapMemoryStatus().setName("Non-Heap");
    applicationStatus.getNonHeapMemoryStatus().setDetails(memoryMXBean.getNonHeapMemoryUsage().toString());
    applicationStatus.getNonHeapMemoryStatus()
            .setInitKb(memoryMXBean.getNonHeapMemoryUsage().getInit() != 0
                    ? memoryMXBean.getNonHeapMemoryUsage().getInit() / 1024
                    : 0);
    applicationStatus.getNonHeapMemoryStatus()
            .setUsedKb(memoryMXBean.getNonHeapMemoryUsage().getUsed() != 0
                    ? memoryMXBean.getNonHeapMemoryUsage().getUsed() / 1024
                    : 0);
    applicationStatus.getNonHeapMemoryStatus()
            .setMaxKb(memoryMXBean.getNonHeapMemoryUsage().getMax() != 0
                    ? memoryMXBean.getNonHeapMemoryUsage().getMax() / 1024
                    : 0);
    applicationStatus.getNonHeapMemoryStatus()
            .setCommitedKb(memoryMXBean.getNonHeapMemoryUsage().getCommitted() != 0
                    ? memoryMXBean.getNonHeapMemoryUsage().getCommitted() / 1024
                    : 0);

    applicationStatus.setLiveThreadCount(threadMXBean.getThreadCount());
    applicationStatus.setTotalThreadCount(threadMXBean.getTotalStartedThreadCount());

    applicationStatus.setStartTime(new Date(runtimeMXBean.getStartTime()));
    applicationStatus.setUpTime(TimeUtil.millisToString(runtimeMXBean.getUptime()));

    for (GarbageCollectorMXBean garbageCollectorMXBean : garbageCollectorMXBeans) {
        applicationStatus.getGarbageCollectionInfos()
                .add(TimeUtil.millisToString(garbageCollectorMXBean.getCollectionTime()) + " - ("
                        + garbageCollectorMXBean.getCollectionCount() + ")");
    }

    for (MemoryPoolMXBean memoryPoolMXBean : memoryPoolMXBeans) {
        MemoryPoolStatus memoryPoolStatus = new MemoryPoolStatus();
        memoryPoolStatus.setName(memoryPoolMXBean.getName() + " - " + memoryPoolMXBean.getType());
        memoryPoolStatus.setDetails(memoryPoolMXBean.getUsage().toString());
        memoryPoolStatus.setInitKb(
                memoryPoolMXBean.getUsage().getInit() != 0 ? memoryPoolMXBean.getUsage().getInit() / 1024 : 0);
        memoryPoolStatus.setUsedKb(
                memoryPoolMXBean.getUsage().getUsed() != 0 ? memoryPoolMXBean.getUsage().getUsed() / 1024 : 0);
        memoryPoolStatus.setMaxKb(
                memoryPoolMXBean.getUsage().getMax() != 0 ? memoryPoolMXBean.getUsage().getMax() / 1024 : 0);
        memoryPoolStatus.setCommitedKb(memoryPoolMXBean.getUsage().getCommitted() != 0
                ? memoryPoolMXBean.getUsage().getCommitted() / 1024
                : 0);

        applicationStatus.getMemoryPools().add(memoryPoolStatus);
    }

    return sendSingleEntityResponse(applicationStatus);
}

From source file:org.apache.hadoop.hbase.util.TestJSONMetricUtil.java

@Test
public void testGetLastGCInfo() {
    List<GarbageCollectorMXBean> gcBeans = ManagementFactory.getGarbageCollectorMXBeans();
    for (GarbageCollectorMXBean bean : gcBeans) {
        ObjectName on = bean.getObjectName();
        Object value = JSONMetricUtil.getValueFromMBean(on, "LastGcInfo");
        LOG.info("Collector Info: " + value);
        if (value != null && value instanceof CompositeData) {
            CompositeData cds = (CompositeData) value;
            assertNotNull(cds.get("duration"));
        }//from   ww w  .j  a va  2s. com
    }
}