Java Code Examples for java.lang.management.GarbageCollectorMXBean

The following examples show how to use java.lang.management.GarbageCollectorMXBean. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: Flink-CEPplus   Source File: MemoryLogger.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Gets the garbage collection statistics from the JVM.
 *
 * @param gcMXBeans The collection of garbage collector beans.
 * @return A string denoting the number of times and total elapsed time in garbage collection.
 */
public static String getGarbageCollectorStatsAsString(List<GarbageCollectorMXBean> gcMXBeans) {
	StringBuilder bld = new StringBuilder("Garbage collector stats: ");
	
	for (GarbageCollectorMXBean bean : gcMXBeans) {
		bld.append('[').append(bean.getName()).append(", GC TIME (ms): ").append(bean.getCollectionTime());
		bld.append(", GC COUNT: ").append(bean.getCollectionCount()).append(']');
		
		bld.append(", ");
	}
	
	if (!gcMXBeans.isEmpty()) {
		bld.setLength(bld.length() - 2);
	}
	
	return bld.toString();
}
 
Example 2
Source Project: Moss   Source File: MossMetricsEndpoint.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 兼容Java 8和Java 10获取GC信息
 * @param haloMetricResponse
 */
private void getGcinfo(HaloMetricResponse haloMetricResponse) {
    List<GarbageCollectorMXBean> garbageCollectorMxBeans = ManagementFactory.getGarbageCollectorMXBeans();
    for (GarbageCollectorMXBean garbageCollectorMXBean : garbageCollectorMxBeans) {
        String name = beautifyGcName(garbageCollectorMXBean.getName());
        String gcCount="gc." + name + ".count";
        String gcTime="gc." + name + ".time";
        if(gcCount.equals("gc.ps_scavenge.count")||gcCount.equals("gc.g1_young_generation.count")){
            haloMetricResponse.setGcPsScavengeCount(String.valueOf(garbageCollectorMXBean.getCollectionCount()));
        }
        if(gcTime.equals("gc.ps_scavenge.time")||gcTime.equals("gc.g1_young_generation.time")){
             haloMetricResponse.setGcPsScavengeTime(String.valueOf(garbageCollectorMXBean.getCollectionTime()));
        }
        if(gcCount.equals("gc.ps_marksweep.count")||gcCount.equals("gc.g1_old_generation.count")){
            haloMetricResponse.setGcPsMarksweepCount(String.valueOf(garbageCollectorMXBean.getCollectionCount()));
        }
        if(gcTime.equals("gc.ps_marksweep.time")||gcTime.equals("gc.g1_old_generation.time")){
            haloMetricResponse.setGcPsMarksweepTime(String.valueOf(garbageCollectorMXBean.getCollectionTime()));
        }
    }
}
 
Example 3
private GcStats collectGcStats() {
  //Collect GC stats by iterating over all GC beans.
  GcStats gcStats = new GcStats();

  for (GarbageCollectorMXBean garbageCollectorMXBean: this.garbageCollectorMXBeans) {
    long count = garbageCollectorMXBean.getCollectionCount();
    double duration = (double) garbageCollectorMXBean.getCollectionTime();
    if (count >= 0) {
      if (YOUNG_GC_TYPES.contains(garbageCollectorMXBean.getName())) {
        gcStats.setMinorCount(gcStats.getMinorCount() + count);
        gcStats.setMinorDuration(gcStats.getMinorDuration() + duration);
      }
      else if (OLD_GC_TYPES.contains(garbageCollectorMXBean.getName())) {
        gcStats.setMajorCount(gcStats.getMajorCount() + count);
        gcStats.setMajorDuration(gcStats.getMajorDuration() + duration);
      } else {
        gcStats.setUnknownCount(gcStats.getUnknownCount() + count);
        gcStats.setUnknownDuration(gcStats.getUnknownDuration() + duration);
      }
    }
  }
  return gcStats;
}
 
Example 4
/**
 * Returns the index that immediately follows the given
 * <var>index</var>. The returned index is strictly greater
 * than the given <var>index</var>, and is contained in the table.
 * <br>If the given <var>index</var> is null, returns the first
 * index in the table.
 * <br>If there are no index after the given <var>index</var>,
 * returns null.
 **/
public SnmpOid getNext(SnmpTableHandler handler, SnmpOid index) {

    // try to call the optimized method
    if (handler instanceof SnmpCachedData)
        return getNext((SnmpCachedData)handler, index);

    // too bad - revert to non-optimized generic algorithm
    SnmpOid next = index;
    do {
        next = handler.getNext(next);
        final Object value = handler.getData(next);
        if (value instanceof GarbageCollectorMXBean)
            // That's the next! return it
            return next;
        // skip to next index...
    } while (next != null);
    return null;
}
 
Example 5
Source Project: fqueue   Source File: JVMMonitor.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 获取GC的时间
 * 
 * @return
 */
public static String getGcTime() {
    StringBuilder sb = new StringBuilder();
    for (GarbageCollectorMXBean bean : garbageCollectorMXBeans) {
        if (sb.length() > 0) {
            sb.append("\r\n");
        }
        if (youngGenCollectorNames.contains(bean.getName())) {
            sb.append("youngGCCount:");
            sb.append(bean.getCollectionCount());
            sb.append("\r\n");
            sb.append("youngGCTime:");
            sb.append(bean.getCollectionTime());
        } else if (fullGenCollectorNames.contains(bean.getName())) {
            sb.append("fullGCCount:");
            sb.append(bean.getCollectionCount());
            sb.append("\r\n");
            sb.append("fullGCTime:");
            sb.append(bean.getCollectionTime());
        }

    }

    return sb.toString();
}
 
Example 6
/**
 * Returns the index that immediately follows the given
 * <var>index</var>. The returned index is strictly greater
 * than the given <var>index</var>, and is contained in the table.
 * <br>If the given <var>index</var> is null, returns the first
 * index in the table.
 * <br>If there are no index after the given <var>index</var>,
 * returns null.
 **/
public SnmpOid getNext(SnmpTableHandler handler, SnmpOid index) {

    // try to call the optimized method
    if (handler instanceof SnmpCachedData)
        return getNext((SnmpCachedData)handler, index);

    // too bad - revert to non-optimized generic algorithm
    SnmpOid next = index;
    do {
        next = handler.getNext(next);
        final Object value = handler.getData(next);
        if (value instanceof GarbageCollectorMXBean)
            // That's the next! return it
            return next;
        // skip to next index...
    } while (next != null);
    return null;
}
 
Example 7
Source Project: LagMonitor   Source File: VmCommand.java    License: MIT License 6 votes vote down vote up
@Override
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
    if (!canExecute(sender, command)) {
        return true;
    }

    //java version info
    displayJavaVersion(sender);

    //java paths
    sendMessage(sender, "Java lib", System.getProperty("sun.boot.library.path", "Unknown"));
    sendMessage(sender, "Java home", System.getProperty("java.home", "Unknown"));
    sendMessage(sender, "Temp path", System.getProperty("java.io.tmpdir", "Unknown"));

    displayRuntimeInfo(sender, ManagementFactory.getRuntimeMXBean());
    displayCompilationInfo(sender, ManagementFactory.getCompilationMXBean());
    displayClassLoading(sender, ManagementFactory.getClassLoadingMXBean());

    //garbage collector
    for (GarbageCollectorMXBean collector : ManagementFactory.getGarbageCollectorMXBeans()) {
        displayCollectorStats(sender, collector);
    }

    return true;
}
 
Example 8
/**
 * Check if the tenured generation are currently using a parallel GC.
 */
protected static boolean isTenuredParallelGC() {
    // Currently the only parallel GC for the tenured generation is PS MarkSweep.
    List<String> parallelGCs = Arrays.asList(new String[] { "PS MarkSweep"});
    try {
        List<GarbageCollectorMXBean> beans = ManagementFactory.getGarbageCollectorMXBeans();
        for (GarbageCollectorMXBean bean : beans) {
            if (parallelGCs.contains(bean.getName())) {
                return true;
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return false;
}
 
Example 9
Source Project: fqueue   Source File: JVMMonitor.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 获取GC的时间
 * 
 * @return
 */
public static String getGcTime() {
    StringBuilder sb = new StringBuilder();
    for (GarbageCollectorMXBean bean : garbageCollectorMXBeans) {
        if (sb.length() > 0) {
            sb.append("\r\n");
        }
        if (youngGenCollectorNames.contains(bean.getName())) {
            sb.append("youngGCCount:");
            sb.append(bean.getCollectionCount());
            sb.append("\r\n");
            sb.append("youngGCTime:");
            sb.append(bean.getCollectionTime());
        } else if (fullGenCollectorNames.contains(bean.getName())) {
            sb.append("fullGCCount:");
            sb.append(bean.getCollectionCount());
            sb.append("\r\n");
            sb.append("fullGCTime:");
            sb.append(bean.getCollectionTime());
        }

    }

    return sb.toString();
}
 
Example 10
Source Project: hottub   Source File: JvmMemGCTableMetaImpl.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * Returns the index that immediately follows the given
 * <var>index</var>. The returned index is strictly greater
 * than the given <var>index</var>, and is contained in the table.
 * <br>If the given <var>index</var> is null, returns the first
 * index in the table.
 * <br>If there are no index after the given <var>index</var>,
 * returns null.
 **/
public SnmpOid getNext(SnmpTableHandler handler, SnmpOid index) {

    // try to call the optimized method
    if (handler instanceof SnmpCachedData)
        return getNext((SnmpCachedData)handler, index);

    // too bad - revert to non-optimized generic algorithm
    SnmpOid next = index;
    do {
        next = handler.getNext(next);
        final Object value = handler.getData(next);
        if (value instanceof GarbageCollectorMXBean)
            // That's the next! return it
            return next;
        // skip to next index...
    } while (next != null);
    return null;
}
 
Example 11
Source Project: hadoop   Source File: JvmMetrics.java    License: Apache License 2.0 6 votes vote down vote up
private void getGcUsage(MetricsRecordBuilder rb) {
  long count = 0;
  long timeMillis = 0;
  for (GarbageCollectorMXBean gcBean : gcBeans) {
    long c = gcBean.getCollectionCount();
    long t = gcBean.getCollectionTime();
    MetricsInfo[] gcInfo = getGcInfo(gcBean.getName());
    rb.addCounter(gcInfo[0], c).addCounter(gcInfo[1], t);
    count += c;
    timeMillis += t;
  }
  rb.addCounter(GcCount, count)
    .addCounter(GcTimeMillis, timeMillis);
  
  if (pauseMonitor != null) {
    rb.addCounter(GcNumWarnThresholdExceeded,
        pauseMonitor.getNumGcWarnThreadholdExceeded());
    rb.addCounter(GcNumInfoThresholdExceeded,
        pauseMonitor.getNumGcInfoThresholdExceeded());
    rb.addCounter(GcTotalExtraSleepTime,
        pauseMonitor.getTotalGcExtraSleepTime());
  }
}
 
Example 12
Source Project: Lavalink   Source File: PrometheusMetrics.java    License: MIT License 6 votes vote down vote up
public PrometheusMetrics() {

        InstrumentedAppender prometheusAppender = new InstrumentedAppender();
        //log metrics
        final LoggerContext factory = (LoggerContext) LoggerFactory.getILoggerFactory();
        final ch.qos.logback.classic.Logger root = factory.getLogger(Logger.ROOT_LOGGER_NAME);
        prometheusAppender.setContext(root.getLoggerContext());
        prometheusAppender.start();
        root.addAppender(prometheusAppender);

        //jvm (hotspot) metrics
        DefaultExports.initialize();

        //gc pause buckets
        final GcNotificationListener gcNotificationListener = new GcNotificationListener();
        for (GarbageCollectorMXBean gcBean : ManagementFactory.getGarbageCollectorMXBeans()) {
            if (gcBean instanceof NotificationEmitter) {
                ((NotificationEmitter) gcBean).addNotificationListener(gcNotificationListener, null, gcBean);
            }
        }

        log.info("Prometheus metrics set up");
    }
 
Example 13
public static void register() {
    // Create an instance to receive events
    NotificationListener listener = new GarbageCollection();

    // Get the MBean server
    MBeanServer server = ManagementFactory.getPlatformMBeanServer();

    // Get the collectors
    List<GarbageCollectorMXBean> beans = ManagementFactory.getGarbageCollectorMXBeans();
    for (GarbageCollectorMXBean bean : beans) {
        // Add the listener to the garbage collector
        try {
            server.addNotificationListener(bean.getObjectName(), listener, null, bean);
        } catch (InstanceNotFoundException e) {
            // ignore
        }
    }
}
 
Example 14
Source Project: jdk8u-jdk   Source File: GcInfoBuilder.java    License: GNU General Public License v2.0 6 votes vote down vote up
GcInfoBuilder(GarbageCollectorMXBean gc, String[] poolNames) {
    this.gc = gc;
    this.poolNames = poolNames;
    this.gcExtItemCount = getNumGcExtAttributes(gc);
    this.gcExtItemNames = new String[gcExtItemCount];
    this.gcExtItemDescs = new String[gcExtItemCount];
    this.gcExtItemTypes = new char[gcExtItemCount];

    // Fill the information about extension attributes
    fillGcAttributeInfo(gc, gcExtItemCount, gcExtItemNames,
                        gcExtItemTypes, gcExtItemDescs);

    // lazily build the CompositeType for the GcInfo
    // including the GC-specific extension attributes
    this.gcInfoCompositeType = null;
}
 
Example 15
Source Project: bender   Source File: BaseHandler.java    License: Apache License 2.0 6 votes vote down vote up
private void getGCStats() {
  long currentGcCount = 0;
  long currentGcDuration = 0;

  for (GarbageCollectorMXBean gc : ManagementFactory.getGarbageCollectorMXBeans()) {
    long count = gc.getCollectionCount();

    if (count >= 0) {
      currentGcCount += count;
    }

    long time = gc.getCollectionTime();

    if (time >= 0) {
      currentGcDuration += time;
    }
  }

  logger.trace("number of GCs: " + (currentGcCount - lastGcCount) + " and time spent in GCs: "
      + (currentGcDuration - lastGcDuration) + "ms");

  lastGcCount = currentGcCount;
  lastGcDuration = currentGcDuration;
}
 
Example 16
Source Project: sofa-lookout   Source File: JvmGcMetricsImporter.java    License: Apache License 2.0 6 votes vote down vote up
static synchronized void refresh() {
    if (System.currentTimeMillis() - lastRefreshedTime <= 1000) {//1s cache
        return;
    }
    List<GarbageCollectorMXBean> garbageCollectorMxBeans = ManagementFactory
        .getGarbageCollectorMXBeans();
    for (GarbageCollectorMXBean garbageCollectorMXBean : garbageCollectorMxBeans) {
        String name = garbageCollectorMXBean.getName();
        long gccount = garbageCollectorMXBean.getCollectionCount();
        long gctime = garbageCollectorMXBean.getCollectionTime();
        GcType type = m.get(name);
        switch (type) {
            case YOUNG:
                youngGCCount = gccount;
                youngGCTime = gctime;
                break;
            case OLD:
                oldGCCount = gccount;
                oldGCTime = gctime;
                break;
        }
    }
    lastRefreshedTime = System.currentTimeMillis();
}
 
Example 17
Source Project: perfmon-agent   Source File: GCDataProviderTest.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Test of getMXBeanClass method, of class GCDataProvider.
 */
public void testGetMXBeanClass() throws Exception {
    System.out.println("getMXBeanClass");
    GCDataProvider instance = new GCDataProvider(new EmulatorMBeanServerConnection(), false);
    Class expResult = GarbageCollectorMXBean.class;
    Class result = instance.getMXBeanClass();
    assertEquals(expResult, result);
}
 
Example 18
public static void main(String[] args) throws InterruptedException {
    List<GarbageCollectorMXBean> list = java.lang.management.ManagementFactory.getGarbageCollectorMXBeans();
    long collectionCountBefore = getCollectionCount(list);
    System.gc();
    long collectionCountAfter = getCollectionCount(list);
    assertLT(collectionCountBefore, collectionCountAfter);
}
 
Example 19
Source Project: signalfx-java   Source File: BasicJvmMetrics.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected Map<String, Long> getSamples() {
    Map<String, Long> samples = new HashMap<String, Long>();
    for (GarbageCollectorMXBean gcBean : allGcBeans) {
        samples.put(gcBean.getName(), gcBean.getCollectionTime());
    }
    return samples;
}
 
Example 20
Source Project: systemds   Source File: Statistics.java    License: Apache License 2.0 5 votes vote down vote up
public static long getJVMgcCount(){
	long ret = 0; 
	
	List<GarbageCollectorMXBean> gcxs = ManagementFactory.getGarbageCollectorMXBeans();
	
	for( GarbageCollectorMXBean gcx : gcxs )
		ret += gcx.getCollectionCount();
	if( ret>0 )
		ret += jvmGCCount;
	
	return ret;
}
 
Example 21
Source Project: jstorm   Source File: GCState.java    License: Apache License 2.0 5 votes vote down vote up
public static long getYoungGenCollectionCount(){
    long youngGCCounts = 0L;
    List<GarbageCollectorMXBean> list = ManagementFactory.getGarbageCollectorMXBeans();
    for (GarbageCollectorMXBean gmx : list) {
        if(youngGenCollectorNames.contains(gmx.getName())){
            youngGCCounts+=gmx.getCollectionCount();
        }
    }
    return youngGCCounts;
}
 
Example 22
Source Project: hottub   Source File: JvmMemGCTableMetaImpl.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * Returns true if the given <var>index</var> is present.
 **/
public boolean contains(SnmpTableHandler handler, SnmpOid index) {
    if (handler.getData(index) instanceof GarbageCollectorMXBean)
        return true;
    // Behaves as if there was nothing at this index...
    //
    return false;
}
 
Example 23
Source Project: bazel   Source File: RetainedHeapLimiter.java    License: Apache License 2.0 5 votes vote down vote up
@VisibleForTesting
static ImmutableList<NotificationEmitter> findTenuredCollectorBeans(
    List<GarbageCollectorMXBean> gcBeans) {
  ImmutableList.Builder<NotificationEmitter> builder = ImmutableList.builder();
  // Examine all collectors and register for notifications from those which collect the tenured
  // space. Normally there is one such collector.
  for (GarbageCollectorMXBean gcBean : gcBeans) {
    for (String name : gcBean.getMemoryPoolNames()) {
      if (isTenuredSpace(name)) {
        builder.add((NotificationEmitter) gcBean);
      }
    }
  }
  return builder.build();
}
 
Example 24
Source Project: hottub   Source File: JvmMemGCTableMetaImpl.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * Returns the data associated with the given index.
 * If the given index is not found, null is returned.
 * Note that returning null does not necessarily means that
 * the index was not found.
 **/
public Object  getData(SnmpTableHandler handler, SnmpOid index) {
    final Object value = handler.getData(index);
    if (value instanceof GarbageCollectorMXBean) return value;
    // Behaves as if there was nothing at this index...
    //
    return null;
}
 
Example 25
/**
 * Returns true if the given <var>index</var> is present.
 **/
public boolean contains(SnmpTableHandler handler, SnmpOid index) {
    if (handler.getData(index) instanceof GarbageCollectorMXBean)
        return true;
    // Behaves as if there was nothing at this index...
    //
    return false;
}
 
Example 26
Source Project: gemfirexd-oss   Source File: VMStats50.java    License: Apache License 2.0 5 votes vote down vote up
private void initGC() {
  List<GarbageCollectorMXBean> l = ManagementFactory.getGarbageCollectorMXBeans();
  for (GarbageCollectorMXBean item : l) {
    if (item.isValid() && !gcMap.containsKey(item)) {
      gcMap.put(item, this.f.createStatistics(gcType, item.getName(), this.id));
    }
  }
}
 
Example 27
Source Project: dragonwell8_jdk   Source File: GCHelper.java    License: GNU General Public License v2.0 5 votes vote down vote up
public static CollectionSummary createFromMxBeans() {
    CollectionSummary summary = new CollectionSummary();
    List<GarbageCollectorMXBean> gcBeans = ManagementFactory.getGarbageCollectorMXBeans();
    for (int c=0; c<gcBeans.size(); c++) {
        GarbageCollectorMXBean currBean = gcBeans.get(c);
        Boolean isYoung = beanCollectorTypes.get(currBean.getName());
        assertNotNull(isYoung, "Unknown MXBean name: " + currBean.getName());
        long collectionTime = currBean.getCollectionTime() * 1000; // Convert from millis to micros.
        summary.add(currBean.getName(), isYoung.booleanValue(), currBean.getCollectionCount(), collectionTime);
    }
    return summary;
}
 
Example 28
private static GarbageCollectorMXBean getCMSGCBean() {
  for (GarbageCollectorMXBean gcBean : ManagementFactory.getGarbageCollectorMXBeans()) {
    if (gcBean.getObjectName().toString().equals("java.lang:type=GarbageCollector,name=ConcurrentMarkSweep")) {
      return gcBean;
    }
  }
  return null;
}
 
Example 29
private static GarbageCollectorMXBean getCMSGCBean() {
  for (GarbageCollectorMXBean gcBean : ManagementFactory.getGarbageCollectorMXBeans()) {
    if (gcBean.getObjectName().toString().equals("java.lang:type=GarbageCollector,name=ConcurrentMarkSweep")) {
      return gcBean;
    }
  }
  return null;
}
 
Example 30
Source Project: pysonar2   Source File: $.java    License: Apache License 2.0 5 votes vote down vote up
public static String getGCStats() {
    long totalGC = 0;
    long gcTime = 0;

    for (GarbageCollectorMXBean gc : ManagementFactory.getGarbageCollectorMXBeans()) {
        long count = gc.getCollectionCount();

        if (count >= 0) {
            totalGC += count;
        }

        long time = gc.getCollectionTime();

        if (time >= 0) {
            gcTime += time;
        }
    }

    StringBuilder sb = new StringBuilder();

    sb.append(banner("memory stats"));
    sb.append("\n- total collections: " + totalGC);
    sb.append("\n- total collection time: " + formatTime(gcTime));

    Runtime runtime = Runtime.getRuntime();
    sb.append("\n- total memory: " + $.printMem(runtime.totalMemory()));

    return sb.toString();
}