Garbage collection notification?

前端 未结 11 487
北海茫月
北海茫月 2020-12-30 19:31

I\'d like to register a callback with the JVM so I know when garbage collection is happening. Is there any way to do this?

EDIT: I want to do this so I can log out

11条回答
  •  孤城傲影
    2020-12-30 20:11

    Java code sample using the GarbageCollectorMXBean referred to in the accepted answer:

    static
    {
        // notification listener. is notified whenever a gc finishes.
        NotificationListener notificationListener = new NotificationListener()
        {
            @Override
            public void handleNotification(Notification notification,Object handback)
            {
                if (notification.getType().equals(GarbageCollectionNotificationInfo.GARBAGE_COLLECTION_NOTIFICATION))
                {
                    // extract garbage collection information from notification.
                    GarbageCollectionNotificationInfo gcInfo = GarbageCollectionNotificationInfo.from((CompositeData) notification.getUserData());
    
                    // access garbage collection information...
                }
            }
        };
    
        // register our listener with all gc beans
        for (GarbageCollectorMXBean gcBean : ManagementFactory.getGarbageCollectorMXBeans())
        {
            NotificationEmitter emitter = (NotificationEmitter) gcBean;
            emitter.addNotificationListener(notificationListener,null,null);
        }
    }
    

    site that has detailed sample code that uses the GarbageCollectorMXBean.

提交回复
热议问题