Talk about JvmGcMetrics’s managementExtensionsPresent

  springboot

Order

This paper mainly studies the managementExtensionsPresent of JvmGcMetrics

JvmGcMetrics

micrometer-core-1.0.3-sources.jar! /io/micrometer/core/instrument/binder/jvm/JvmGcMetrics.java

@NonNullApi
@NonNullFields
public class JvmGcMetrics implements MeterBinder {

    private static final Logger logger = LoggerFactory.getLogger(JvmGcMetrics.class);

    private boolean managementExtensionsPresent = isManagementExtensionsPresent();

    @Override
    public void bindTo(MeterRegistry registry) {
        AtomicLong maxDataSize = new AtomicLong(0L);
        Gauge.builder("jvm.gc.max.data.size", maxDataSize, AtomicLong::get)
            .tags(tags)
            .description("Max size of old generation memory pool")
            .baseUnit("bytes")
            .register(registry);

        AtomicLong liveDataSize = new AtomicLong(0L);

        Gauge.builder("jvm.gc.live.data.size", liveDataSize, AtomicLong::get)
            .tags(tags)
            .description("Size of old generation memory pool after a full GC")
            .baseUnit("bytes")
            .register(registry);

        Counter promotedBytes = Counter.builder("jvm.gc.memory.promoted").tags(tags)
            .baseUnit("bytes")
            .description("Count of positive increases in the size of the old generation memory pool before GC to after GC")
            .register(registry);

        Counter allocatedBytes = Counter.builder("jvm.gc.memory.allocated").tags(tags)
            .baseUnit("bytes")
            .description("Incremented for an increase in the size of the young generation memory pool after one GC to before the next")
            .register(registry);

        if (this.managementExtensionsPresent) {
            // start watching for GC notifications
            final AtomicLong youngGenSizeAfter = new AtomicLong(0L);

            for (GarbageCollectorMXBean mbean : ManagementFactory.getGarbageCollectorMXBeans()) {
                if (mbean instanceof NotificationEmitter) {
                    ((NotificationEmitter) mbean).addNotificationListener((notification, ref) -> {
                        final String type = notification.getType();
                        if (type.equals(GarbageCollectionNotificationInfo.GARBAGE_COLLECTION_NOTIFICATION)) {
                            CompositeData cd = (CompositeData) notification.getUserData();
                            GarbageCollectionNotificationInfo notificationInfo = GarbageCollectionNotificationInfo.from(cd);

                            if (isConcurrentPhase(notificationInfo.getGcCause())) {
                                Timer.builder("jvm.gc.concurrent.phase.time")
                                        .tags(tags)
                                        .tags("action", notificationInfo.getGcAction(), "cause", notificationInfo.getGcCause())
                                        .description("Time spent in concurrent phase")
                                        .register(registry)
                                        .record(notificationInfo.getGcInfo().getDuration(), TimeUnit.MILLISECONDS);
                            } else {
                                Timer.builder("jvm.gc.pause")
                                        .tags(tags)
                                        .tags("action", notificationInfo.getGcAction(),
                                                "cause", notificationInfo.getGcCause())
                                        .description("Time spent in GC pause")
                                        .register(registry)
                                        .record(notificationInfo.getGcInfo().getDuration(), TimeUnit.MILLISECONDS);
                            }

                            GcInfo gcInfo = notificationInfo.getGcInfo();

                            // Update promotion and allocation counters
                            final Map<String, MemoryUsage> before = gcInfo.getMemoryUsageBeforeGc();
                            final Map<String, MemoryUsage> after = gcInfo.getMemoryUsageAfterGc();

                            if (oldGenPoolName != null) {
                                final long oldBefore = before.get(oldGenPoolName).getUsed();
                                final long oldAfter = after.get(oldGenPoolName).getUsed();
                                final long delta = oldAfter - oldBefore;
                                if (delta > 0L) {
                                    promotedBytes.increment(delta);
                                }

                                // Some GC implementations such as G1 can reduce the old gen size as part of a minor GC. To track the
                                // live data size we record the value if we see a reduction in the old gen heap size or
                                // after a major GC.
                                if (oldAfter < oldBefore || GcGenerationAge.fromName(notificationInfo.getGcName()) == GcGenerationAge.OLD) {
                                    liveDataSize.set(oldAfter);
                                    final long oldMaxAfter = after.get(oldGenPoolName).getMax();
                                    maxDataSize.set(oldMaxAfter);
                                }
                            }

                            if (youngGenPoolName != null) {
                                final long youngBefore = before.get(youngGenPoolName).getUsed();
                                final long youngAfter = after.get(youngGenPoolName).getUsed();
                                final long delta = youngBefore - youngGenSizeAfter.get();
                                youngGenSizeAfter.set(youngAfter);
                                if (delta > 0L) {
                                    allocatedBytes.increment(delta);
                                }
                            }
                        }
                    }, null, null);
                }
            }
        }
    }

    //......
}

It can be seen here that the managementExtensionsPresent will be judged first, and the timer indicator of jvm.gc.concurrent.phase.time and jvm.gc.pause will be registered only if there is one.

isManagementExtensionsPresent

    private static boolean isManagementExtensionsPresent() {
        try {
            Class.forName("com.sun.management.GarbageCollectionNotificationInfo", false,
                JvmGcMetrics.class.getClassLoader());
            return true;
        } catch (Throwable e) {
            // We are operating in a JVM without access to this level of detail
            logger.warn("GC notifications will not be available because " +
                "com.sun.management.GarbageCollectionNotificationInfo is not present");
            return false;
        }
    }

If you can find COM.Sun.Management.GarbageCollectionNotificationInfo, it will be true.

  • Failed to load
/ # jshell
Apr 12, 2018 4:39:07 PM java.util.prefs.FileSystemPreferences$1 run
INFO: Created user preferences directory.
|  Welcome to JShell -- Version 10
|  For an introduction type: /help intro

jshell> Class.forName("com.sun.management.GarbageCollectionNotificationInfo", false, Object.class.getClassLoader())
|  java.lang.ClassNotFoundException thrown: com/sun/management/GarbageCollectionNotificationInfo
|        at Class.forName0 (Native Method)
|        at Class.forName (Class.java:374)
|        at (#1:1)

jshell> /exit
|  Goodbye
  • Loading success
/ # jshell
Apr 12, 2018 4:05:30 PM java.util.prefs.FileSystemPreferences$1 run
INFO: Created user preferences directory.
|  Welcome to JShell -- Version 10
|  For an introduction type: /help intro

jshell> Class.forName("com.sun.management.GarbageCollectionNotificationInfo", false, Object.class.getClassLoader())
$1 ==> class com.sun.management.GarbageCollectionNotificationInfo
jshell> /exit
|  Goodbye

GarbageCollectionNotificationInfo

/Library/Java/JavaVirtualMachines/jdk-10.jdk/Contents/Home/lib/src.zip! /jdk.management/com/sun/management/GarbageCollectionNotificationInfo.java

package com.sun.management;

import javax.management.openmbean.CompositeData;
import javax.management.openmbean.CompositeDataView;
import javax.management.openmbean.CompositeType;
import com.sun.management.internal.GarbageCollectionNotifInfoCompositeData;

public class GarbageCollectionNotificationInfo implements  CompositeDataView {
    //......
}

Judging from the classpath, it is in the module of jdk.management and the package is com.sun.management If the metrics can have the timer indicators of jvm.gc.concurrent.phase.time and jvm.gc.pause, then com.sun.management.garbageconnectionnotificationinfo is required in the jdk. by default, yes. if your jdk has jlink, java.management and jdk.management are required

Java.management and jdk.management

Management-related jmod

➜  jmods ls | grep management
java.management.jmod
java.management.rmi.jmod
jdk.internal.vm.compiler.management.jmod
jdk.management.agent.jmod
jdk.management.jmod

java.management

jmod describe java.management.jmod
java.management@10
exports java.lang.management
exports javax.management
exports javax.management.loading
exports javax.management.modelmbean
exports javax.management.monitor
exports javax.management.openmbean
exports javax.management.relation
exports javax.management.remote
exports javax.management.timer
requires java.base mandated
uses javax.management.remote.JMXConnectorProvider
uses javax.management.remote.JMXConnectorServerProvider
uses sun.management.spi.PlatformMBeanProvider
provides javax.security.auth.spi.LoginModule with com.sun.jmx.remote.security.fileloginmodule
qualified exports com.sun.jmx.remote.internal to java.management.rmi jdk.management.agent
qualified exports com.sun.jmx.remote.security to java.management.rmi jdk.management.agent
qualified exports com.sun.jmx.remote.util to java.management.rmi
qualified exports sun.management to jdk.jconsole jdk.management jdk.management.agent
qualified exports sun.management.counter to jdk.management.agent
qualified exports sun.management.counter.perf to jdk.management.agent
qualified exports sun.management.spi to jdk.internal.vm.compiler.management jdk.management
contains com.sun.jmx.defaults
contains com.sun.jmx.interceptor
contains com.sun.jmx.mbeanserver
platform macos-amd64

You can see the java.management module qualified exports sun.management to jdk.jconsole jdk.managejdk.management.agent. note that this is sun.management.

This mod provides jmx related class libraries, without which, relying on jxm’s functions will report errors, such as

java.lang.IllegalStateException: Logback configuration error detected:
ERROR in ch.qos.logback.core.joran.spi.Interpreter@4:23 - no applicable action for [jmxConfigurator], current ElementPath  is [[configuration][jmxConfigurator]]
    at org.springframework.boot.logging.logback.LogbackLoggingSystem.loadConfiguration(LogbackLoggingSystem.java:166)
    at org.springframework.boot.logging.logback.LogbackLoggingSystem.reinitialize(LogbackLoggingSystem.java:212)
    at org.springframework.boot.logging.AbstractLoggingSystem.initializeWithConventions(AbstractLoggingSystem.java:75)
    at org.springframework.boot.logging.AbstractLoggingSystem.initialize(AbstractLoggingSystem.java:60)
    at org.springframework.boot.logging.logback.LogbackLoggingSystem.initialize(LogbackLoggingSystem.java:114)
    at org.springframework.boot.context.logging.LoggingApplicationListener.initializeSystem(LoggingApplicationListener.java:264)
    at org.springframework.boot.context.logging.LoggingApplicationListener.initialize(LoggingApplicationListener.java:237)
    at org.springframework.boot.context.logging.LoggingApplicationListener.onApplicationEnvironmentPreparedEvent(LoggingApplicationListener.java:200)
    at org.springframework.boot.context.logging.LoggingApplicationListener.onApplicationEvent(LoggingApplicationListener.java:173)
    at org.springframework.context.event.SimpleApplicationEventMulticaster.doInvokeListener(SimpleApplicationEventMulticaster.java:172)
    at org.springframework.context.event.SimpleApplicationEventMulticaster.invokeListener(SimpleApplicationEventMulticaster.java:165)
    at org.springframework.context.event.SimpleApplicationEventMulticaster.multicastEvent(SimpleApplicationEventMulticaster.java:139)
    at org.springframework.context.event.SimpleApplicationEventMulticaster.multicastEvent(SimpleApplicationEventMulticaster.java:127)
    at org.springframework.boot.context.event.EventPublishingRunListener.environmentPrepared(EventPublishingRunListener.java:74)
    at org.springframework.boot.SpringApplicationRunListeners.environmentPrepared(SpringApplicationRunListeners.java:54)
    at org.springframework.boot.SpringApplication.prepareEnvironment(SpringApplication.java:358)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:317)
    at org.springframework.boot.builder.SpringApplicationBuilder.run(SpringApplicationBuilder.java:137)

jdk.management

jmod describe jdk.management.jmod
jdk.management@10
exports com.sun.management
requires java.base mandated
requires java.management transitive
provides sun.management.spi.PlatformMBeanProvider with com.sun.management.internal.platformmbeanproviderimpl
contains com.sun.management.internal
platform macos-amd64

You can see that jdk.management exported com.sun.management. note that this is com.sun.management.

Summary

If you want to have jvm.gc.concurrent.phase.time and jvm.gc.pause timer indicators in metrics, you need to add jdk.management module. garbageconnectionnotificationinfo is in the com.sun.management package, not the sun.management package. JvmGcMetrics uses jmx, so java.lang.management module is also needed.

doc