import javax.management.*; import javax.management.openmbean.CompositeData; import com.sun.management.GarbageCollectionNotificationInfo; import com.sun.management.GcInfo; static AutoCloseable onGCNotification(final VF1 theListener) { final NotificationListener listener = new NotificationListener { public void handleNotification(Notification notification, O handback) { // extract garbage collection information from notification. GarbageCollectionNotificationInfo gcInfo = GarbageCollectionNotificationInfo.from((CompositeData) notification.getUserData()); pcallF(theListener, gcInfo); } }; for (GarbageCollectorMXBean gcBean : ManagementFactory.getGarbageCollectorMXBeans()) ((NotificationEmitter) gcBean).addNotificationListener(listener, null, null); ret autoCloseable { for (GarbageCollectorMXBean gcBean : ManagementFactory.getGarbageCollectorMXBeans()) ((NotificationEmitter) gcBean).removeNotificationListener(listener, null, null); }; }