Search code examples
javagarbage-collectiondetection

Java Garbage Cleaner detector


How to detect java garbage cleaner?

It can be useful, when you want to do some experements on java or learn how java works.


Solution

  • There are different ways to detect it:

    1. Logging: You can enable GC logging in the Java Virtual Machine (JVM) to track when garbage collection occurs. This logging provides detailed information about the frequency, duration, and type of garbage collection events. To enable GC logging, you can use JVM options like -XX:+PrintGC and -XX:+PrintGCDetails.

    2. JVisualVM: Java VisualVM is a monitoring, troubleshooting, and profiling tool that is included with the Java Development Kit (JDK). It provides a graphical interface to monitor the JVM and applications running on it, including garbage collection activity. You can connect JVisualVM to your Java application and monitor GC activity in real-time. It displays various metrics related to memory usage, including heap usage and garbage collection events.

    3. GC Notifications: Since Java 9, you can use the GarbageCollectorMXBean class to monitor garbage collection activity programmatically. Here's an example:

    import java.lang.management.GarbageCollectorMXBean;
    import java.lang.management.ManagementFactory;
    import javax.management.NotificationEmitter;
    import javax.management.NotificationListener;
    import javax.management.openmbean.CompositeData;
    
    public class GCNotifier {
        public static void main(String[] args) {
            for (GarbageCollectorMXBean gc : ManagementFactory.getGarbageCollectorMXBeans()) {
                NotificationEmitter emitter = (NotificationEmitter) gc;
                emitter.addNotificationListener(new NotificationListener() {
                    @Override
                    public void handleNotification(javax.management.Notification notification, Object handback) {
                        if (notification.getType().equals(GarbageCollectionNotificationInfo.GARBAGE_COLLECTION_NOTIFICATION)) {
                            GarbageCollectionNotificationInfo info = GarbageCollectionNotificationInfo.from((CompositeData) notification.getUserData());
                            System.out.println("GC Event: " + info.getGcName() + ", Duration: " + info.getGcInfo().getDuration());
                        }
                    }
                }, null, null);
            }
        }
    }