I am trying to publish out the garbage collection statistics for my services. Few of them are running on JDK 7 and few of them on JDK8.
I have read in the question: Can you get basic GC stats in Java? that we can get the total Garbage collection count via the MBean. But I am trying to look at a slightly different picture.
I am trying to publish out the major and minor collection count separately. The above method will get the total collection count and not segregating out into minor and major.
What I have tried to do?
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;
}
}
The collectors I get in the list are: PS Scavenge and PS MarkSweep.
For PS Scavenge the pool names are: PS Eden Space, PS Survivor Space.
For PS MarkSweep the pool names are: PS Eden Space, PS Survivor Space, PS Old Gen, PS Perm Gen
JVM parameters I am using:
-XX:+UseParNewGC -XX:+UseConcMarkSweepGC -XX:+DisableExplicitGC.
No usecmsinitiatingoccupancyonly and cmsinitiatingoccupancyfraction is mentioned.
Thanks in advance.
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());
This works both for JDK 7 and JDK 8 for all typical collectors: