//copied from http://www.fasterj.com/articles/gcnotifs.shtml
private void registerGarbageCollectionListener() {
List<GarbageCollectorMXBean> gcbeans = java.lang.management.ManagementFactory.getGarbageCollectorMXBeans();
for (GarbageCollectorMXBean gcbean : gcbeans) {
NotificationEmitter emitter = (NotificationEmitter) gcbean;
NotificationListener listener = new NotificationListener() {
//keep a count of the total time spent in GCs
long totalGcDuration = 0;
//implement the notifier callback handler
@Override
public void handleNotification(Notification notification, Object handback) {
if (notification.getType().equals(GarbageCollectionNotificationInfo.GARBAGE_COLLECTION_NOTIFICATION)) {
//get the information associated with this notification
GarbageCollectionNotificationInfo info = GarbageCollectionNotificationInfo.from((CompositeData) notification.getUserData());
Map<String, MemoryUsage> mem = info.getGcInfo().getMemoryUsageAfterGc();
for (Map.Entry<String, MemoryUsage> entry : mem.entrySet()) {
String name = entry.getKey();
MemoryUsage memoryDetail = entry.getValue();
if ("PS Old Gen".equals(name)) {
memoryStatus = findStatus(memoryDetail.getUsed(), memoryDetail.getMax());
}
}
totalGcDuration += info.getGcInfo().getDuration();
}
}
};
//Add the listener
emitter.addNotificationListener(listener, null, null);
}
}