java.lang.management.GarbageCollectorMXBean Java Examples

The following examples show how to use java.lang.management.GarbageCollectorMXBean. 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 File: JvmMemGCTableMetaImpl.java    From TencentKona-8 with 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 #2
Source File: MossMetricsEndpoint.java    From Moss with 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
Source File: MemoryLogger.java    From Flink-CEPplus with 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 #4
Source File: ContainerHealthMetricsService.java    From incubator-gobblin with Apache License 2.0 6 votes vote down vote up
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 #5
Source File: JvmMemGCTableMetaImpl.java    From openjdk-jdk8u with 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 #6
Source File: JVMMonitor.java    From fqueue with 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 #7
Source File: VmCommand.java    From LagMonitor with 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
Source File: JstatGcCapacityResults.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * 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 File: JVMMonitor.java    From fqueue with 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 File: JvmMemGCTableMetaImpl.java    From hottub with 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 File: JvmMetrics.java    From hadoop with 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 File: PrometheusMetrics.java    From Lavalink with 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
Source File: GarbageCollection.java    From tracing-framework with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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 File: GcInfoBuilder.java    From jdk8u-jdk with 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 File: BaseHandler.java    From bender with 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 File: JvmGcMetricsImporter.java    From sofa-lookout with 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 File: ProcessUtils.java    From Shadbot with GNU General Public License v3.0 5 votes vote down vote up
/**
 * @return The total number of Garbage Collection count.
 */
public static long getGCCount() {
    return ManagementFactory.getGarbageCollectorMXBeans()
            .stream()
            .map(GarbageCollectorMXBean::getCollectionCount)
            .mapToInt(Long::intValue)
            .filter(count -> count > 0)
            .sum();
}
 
Example #18
Source File: SystemMetrics.java    From hugegraph with Apache License 2.0 5 votes vote down vote up
private Map<String, Object> getGarbageCollectionMetrics() {
    Map<String, Object> metrics = new LinkedHashMap<>();
    List<GarbageCollectorMXBean> gcMxBeans = ManagementFactory
                                             .getGarbageCollectorMXBeans();
    for (GarbageCollectorMXBean gcMxBean : gcMxBeans) {
        String name = formatName(gcMxBean.getName());
        metrics.put(name + "_count", gcMxBean.getCollectionCount());
        metrics.put(name + "_time", gcMxBean.getCollectionTime());
    }
    metrics.put("time_unit", "ms");
    return metrics;
}
 
Example #19
Source File: JvmMemGCTableMetaImpl.java    From jdk8u-jdk with 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 #20
Source File: JvmMemGCTableMetaImpl.java    From jdk8u60 with 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 #21
Source File: JvmMemGCTableMetaImpl.java    From jdk8u60 with 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 #22
Source File: GCDataProviderTest.java    From perfmon-agent with 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 #23
Source File: JVMGC.java    From mpush with Apache License 2.0 5 votes vote down vote up
public JVMGC() {
    for (GarbageCollectorMXBean item : ManagementFactory.getGarbageCollectorMXBeans()) {
        String name = item.getName();
        if (youngGcName.contains(name)) {
            yongGc = item;
        } else if (fullGcName.contains(name)) {
            fullGc = item;
        }
    }
}
 
Example #24
Source File: TestDisableExplicitGC.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
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 #25
Source File: MemoryMonitor.java    From beam with Apache License 2.0 5 votes vote down vote up
@Override
public long totalGCTimeMilliseconds() {
  long inGC = 0;
  for (GarbageCollectorMXBean gc : ManagementFactory.getGarbageCollectorMXBeans()) {
    inGC += gc.getCollectionTime();
  }
  return inGC;
}
 
Example #26
Source File: BasicJvmMetrics.java    From signalfx-java with 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 #27
Source File: Statistics.java    From systemds with 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 #28
Source File: JVMMetrics.java    From incubator-heron with Apache License 2.0 5 votes vote down vote up
private void updateGcCounts() {
  long totalCount = 0;
  for (GarbageCollectorMXBean bean : ManagementFactory.getGarbageCollectorMXBeans()) {
    long collectionCount = bean.getCollectionCount();
    totalCount += collectionCount;
    // Replace all non alpha-numeric characters to '-'
    String normalizedKeyName = bean.getName().replaceAll("[^\\w]", "-");
    jvmGCCountPerGCType.safeScope(normalizedKeyName).setValue(collectionCount);
  }
  jvmGCCount.setValue(totalCount);
}
 
Example #29
Source File: GarbageCollectorExports.java    From client_java with Apache License 2.0 5 votes vote down vote up
public List<MetricFamilySamples> collect() {
  SummaryMetricFamily gcCollection = new SummaryMetricFamily(
      "jvm_gc_collection_seconds",
      "Time spent in a given JVM garbage collector in seconds.",
      Collections.singletonList("gc"));
  for (final GarbageCollectorMXBean gc : garbageCollectors) {
      gcCollection.addMetric(
          Collections.singletonList(gc.getName()),
          gc.getCollectionCount(),
          gc.getCollectionTime() / MILLISECONDS_PER_SECOND);
  }
  List<MetricFamilySamples> mfs = new ArrayList<MetricFamilySamples>();
  mfs.add(gcCollection);
  return mfs;
}
 
Example #30
Source File: GarbageCollection.java    From tracing-framework with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public void handleNotification(Notification notification, Object handback) {
    // Make sure it's the right notification type
    if (!notification.getType().equals(GarbageCollectionNotificationInfo.GARBAGE_COLLECTION_NOTIFICATION))
        return;

    // Extract the GcInfo as appropriate, working around the OpenJDK GcInfo
    // cycles/milliseconds bug
    GarbageCollectorMXBean bean = (GarbageCollectorMXBean) handback;
    GarbageCollectionNotificationInfo info = getInfo(notification);
    GcInfo gc = getGcInfo(info, bean);

    // Extract the fields we want to include in the X-Trace report
    String startTime = Long.toString(JVMStartTimeMillis + gc.getStartTime());
    String duration = Long.toString(gc.getDuration());
    String action = info.getGcAction();
    String cause = info.getGcCause();
    String name = info.getGcName();

    XTraceReport report = XTraceReport.create();
    report.addStandardFields();
    report.builder.setTaskId(taskid);
    report.applyDecorators();
    report.setMessage("Garbage Collection Event");
    report.builder.addKey("Operation").addValue("GC");
    report.builder.addKey("GcStart").addValue(startTime);
    report.builder.addKey("GcDuration").addValue(duration);
    report.builder.addKey("GcAction").addValue(action);
    report.builder.addKey("GcCause").addValue(cause);
    report.builder.addKey("GcName").addValue(name);
    report.builder.addTags("GarbageCollection");
    report.builder.addTags(Utils.getProcessName());
    XTrace.getDefaultReporter().send(report);
}