A useful metric for determining when the JVM is about to get into memory/GC trouble

后端 未结 3 1268
Happy的楠姐
Happy的楠姐 2020-12-16 16:46

I have a scala data processing application that 95% of the time can handle the data thrown at it in memory. The remaining 5% if left unchecked doesn\'t usually hit OutOf

3条回答
  •  再見小時候
    2020-12-16 17:12

    One reliable way is to register a notification listener on GC events and check the memory health after all Full GC events. Directly after a full GC event, the memory used is your actual live set of data. If you at that point in time are low on free memory it is probably time start flusing to disk.

    This way you can avoid false positives that often happens when you try to check memory with no knowledge of when a full GC has occurred, for example when using the MEMORY_THRESHOLD_EXCEEDED notification type.

    You can register a notification listener and handle Full GC events using something like the following code:

    // ... standard imports ommitted
    import com.sun.management.GarbageCollectionNotificationInfo;
    
    public static void installGCMonitoring() {
        List gcBeans = ManagementFactory.getGarbageCollectorMXBeans();
        for (GarbageCollectorMXBean gcBean : gcBeans) {
            NotificationEmitter emitter = (NotificationEmitter) gcBean;
            NotificationListener listener = notificationListener();
            emitter.addNotificationListener(listener, null, null);
        }
    }
    
    private static NotificationListener notificationListener() {
        return 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());
                    String gctype = info.getGcAction();
                    if (gctype.contains("major")) {
                        // We are only interested in full (major) GCs
                        Map mem = info.getGcInfo().getMemoryUsageAfterGc();
                        for (Entry entry : mem.entrySet()) {
                            String memoryPoolName = entry.getKey();
                            MemoryUsage memdetail = entry.getValue();
                            long memMax = memdetail.getMax();
                            long memUsed = memdetail.getUsed();
                            // Use the memMax/memUsed of the pool you are interested in (probably old gen)
                            // to determine memory health.
                        }
                    }
                }
            }
        };
    }
    

    Cred to this article where we first got this idea from.

提交回复
热议问题