1、Jstat方式
public class Main {
private static final String YOUNG_GC_MONITOR_NAME = "sun.gc.collector.0.invocations";
private static final String FULL_GC_MONITOR_NAME = "sun.gc.collector.1.invocations";
public static void main(String[] args) throws URISyntaxException, MonitorException {
/*
Returns the managed bean for the runtime system of
the Java virtual machine.
*/
String name = ManagementFactory.getRuntimeMXBean().getName();
//获取pid
String pid = name.substring(0, name.indexOf("@"));
VmIdentifier vmId = new VmIdentifier(pid);
MonitoredHost monitoredHost = MonitoredHost.getMonitoredHost(vmId);
MonitoredVm monitoredVm = monitoredHost.getMonitoredVm(vmId, 0);
Monitor youngGCMonitor = monitoredVm.findByName(YOUNG_GC_MONITOR_NAME);
Monitor fullGCMonitor = monitoredVm.findByName(FULL_GC_MONITOR_NAME);
System.out.println(youngGCMonitor.getValue());
System.out.println(fullGCMonitor.getValue());
}
}
2、收集器名称方式
//新生代GC收集器名称
private Set<String> younggcAlgorithm = new LinkedHashSet<String>() {
private static final long serialVersionUID = -2953196532584721351L;
{
this.add("Copy");
this.add("ParNew");
this.add("PS Scavenge");
this.add("G1 Young Generation");
}
};
//老年代GC收集器名称
private Set<String> oldgcAlgorithm = new LinkedHashSet<String>() {
private static final long serialVersionUID = -8267829533109860610L;
{
this.add("MarkSweepCompact");
this.add("PS MarkSweep");
this.add("ConcurrentMarkSweep");
this.add("G1 Old Generation");
}
};
//核心代码
Iterator iterator = ManagementFactory.getGarbageCollectorMXBeans().iterator();
while(iterator.hasNext()) {
GarbageCollectorMXBean garbageCollector = (GarbageCollectorMXBean)iterator.next();
String gcAlgorithm = garbageCollector.getName();
if (this.younggcAlgorithm.contains(gcAlgorithm)) {
youngGcCount += garbageCollector.getCollectionCount();
} else if (this.oldgcAlgorithm.contains(gcAlgorithm)) {
oldGCount += garbageCollector.getCollectionCount();
} else {
//...
}
}
关于GC收集器的名称,可以参考:这里