本文主要研究下JvmGcMetrics的managementExtensionsPresentjava
micrometer-core-1.0.3-sources.jar!/io/micrometer/core/instrument/binder/jvm/JvmGcMetrics.javaspring
@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); } } } } //...... }
能夠看到這裏會先判斷managementExtensionsPresent,若是有才會註冊jvm.gc.concurrent.phase.time以及jvm.gc.pause的timer指標
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; } }
這裏的話是採用類加載來判斷的,若是能找到com.sun.management.GarbageCollectionNotificationInfo則爲true
/ # 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
/ # 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
/Library/Java/JavaVirtualMachines/jdk-10.jdk/Contents/Home/lib/src.zip!/jdk.management/com/sun/management/GarbageCollectionNotificationInfo.javashell
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 { //...... }
從類路徑看,是在jdk.management的模塊裏頭,所在包爲com.sun.management。若是要是的metrics能有jvm.gc.concurrent.phase.time以及jvm.gc.pause的timer指標的話,則要求jdk裏頭有com.sun.management.GarbageCollectionNotificationInfo,默認是有的,若是你的jdk進行了jlink的話,則須要加上java.management以及jdk.management
➜ jmods ls | grep management java.management.jmod java.management.rmi.jmod jdk.internal.vm.compiler.management.jmod jdk.management.agent.jmod jdk.management.jmod
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
能夠看到java.management模塊qualified exports sun.management to jdk.jconsole jdk.management jdk.management.agent,注意這裏是sun.management
這個mod提供了jmx相關類庫,不加的話,依賴jxm的功能會報錯,好比macos
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)
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
能夠看到jdk.management導出了com.sun.management,注意這裏是com.sun.management
要想在metrics裏頭有jvm.gc.concurrent.phase.time以及jvm.gc.pause的timer指標,則須要添加jdk.management模塊,GarbageCollectionNotificationInfo是在com.sun.management包裏頭,而不是sun.management包。JvmGcMetrics用到了jmx,所以也須要加上java.lang.management模塊。segmentfault