如何在 JDK 7 和 JDK 8 中获取次要和主要垃圾回收计数

How to get minor and major garbage collection count in JDK 7 and JDK 8

我正在尝试发布我的服务的垃圾收集统计信息。其中很少有人 运行 在 JDK 7 上,很少有人在 JDK8.

我在问题 Can you get basic GC stats in Java? 中读到,我们可以通过 MBean 获得总的垃圾收集计数。但我正在尝试查看略有不同的图片。

我正在尝试分别发布主要和次要馆藏计数。上面的方法将得到总的收集计数,而不是分成次要和主要。

我做了什么?

List<GarbageCollectorMXBean> listOfGarbageCollectionMBeans = ManagementFactory.getGarbageCollectorMXBeans();
Stats majorGCStats= null;
Stats minorGcStats = null;
for (GarbageCollectorMXBean gcMBean: listOfGarbageCollectionMBeans ) {
Stats stats = new Stats();
// in the method isMajorCollector, trying to identify if the collector is for major or minor depending on pool name
  if (isMajorCollector(gcMBean.getMemoryPoolNames())) {
    majorGCStats= stats;
  }
  else{
     minorGCStats= stats;
  }
  //Collection_MAP is a HashMap of minorGC vs Stats and majorGC vs Stats
  COLLECTION_MAP.put(stats.getName(), stats);
}

public boolean isMajorCollector(String[] poolNames){
    for (final String pool : pools) {
      if (pool.contains("Perm")|| pool.contains("Old")) {
        return true;
      }
    }
    return false;
   }
}


// An inner class to hold the time and name
class Stats{
 private String name;
 private long time;

 public void setTime(final long time){
   this.time= time;
 }

 public void setName(final String name){
   this.name=name;
 }

 public String getName(){
  return this.name;
 }

 public long getTime(){
   return this.time;
  }
 }

我在列表中获得的收集器是:PS Scavenge 和 PS MarkSweep。

对于 PS 清除池名称是:PS Eden Space、PS Survivor Space。

对于 PS MarkSweep,池名称是:PS Eden Space、PS Survivor Space、PS Old Gen、PS 烫发一代

我使用的JVM参数:

-XX:+UseParNewGC -XX:+UseConcMarkSweepGC -XX:+DisableExplicitGC.

没有提到 usecmsinitiatingoccupancyonly 和 cmsinitiatingoccupancyfraction。

提前致谢。

 List<GarbageCollectorMXBean> gcMXBeans = ManagementFactory.getGarbageCollectorMXBeans();
 System.out.println("Minor GC count = " + gcMXBeans.get(0).getCollectionCount());
 System.out.println("Major GC count = " + gcMXBeans.get(1).getCollectionCount());

这适用于所有典型收集器的 JDK 7 和 JDK 8:

  • -XX:+UseConcMarkSweepGC
  • -XX:+UseParallelGC
  • -XX:+UseSerialGC
  • -XX:+UseG1GC