How to retrieve the number of full garbage collections in Java using JMX?
One way to implement in Java using JMX (Java Management Extensions) is to get the number of Full GC occurrences through MBeans.
- Create an MBean interface with the following code that includes a method to retrieve the number of Full GC occurrences:
public interface GCStatsMBean {
long getFullGCCount();
}
- Create a class implementing the MBean interface that includes a method for retrieving the number of Full GC occurrences.
public class GCStats implements GCStatsMBean {
private long fullGCCount = 0;
public long getFullGCCount() {
return fullGCCount;
}
public void incrementFullGCCount() {
fullGCCount++;
}
}
- Register this class as an MBean and expose it to the JMX server.
public static void main(String[] args) throws Exception {
MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
GCStats gcStats = new GCStats();
ObjectName name = new ObjectName("com.example:type=GCStats");
mbs.registerMBean(gcStats, name);
// 监听GC事件,并在发生Full GC时调用incrementFullGCCount方法
NotificationEmitter emitter = (NotificationEmitter) ManagementFactory.getGarbageCollectorMXBeans().get(0);
emitter.addNotificationListener(new NotificationListener() {
@Override
public void handleNotification(Notification notification, Object handback) {
if (notification.getType().equals(GarbageCollectionNotificationInfo.GARBAGE_COLLECTION_NOTIFICATION)) {
GarbageCollectionNotificationInfo info = GarbageCollectionNotificationInfo.from((CompositeData) notification.getUserData());
if (info.getGcAction().equals("end of major GC")) {
gcStats.incrementFullGCCount();
}
}
}
}, null, null);
// 等待程序运行
Thread.sleep(Long.MAX_VALUE);
}
We can retrieve the number of Full GCs in JMX by calling the getFullGCCount method of GCStatsMBean.
More tutorials
How to install and use Java JMX?(Opens in a new browser tab)
Sort the Java Collections using the sort() method.(Opens in a new browser tab)
What is the method for retrieving a timestamp in Linux?(Opens in a new browser tab)
Tutorials on Java EE(Opens in a new browser tab)
How can I utilize PhotoRec to retrieve erased files?(Opens in a new browser tab)