序
本文主要研究下JvmGcMetrics的managementExtensionsPresent
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);
}
}
}
}
//......
}
可以看到這里會先判斷managementExtensionsPresent,如果有才會注冊jvm.gc.concurrent.phase.time以及jvm.gc.pause的timer指標(biāo)
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;
}
}
這里的話是采用類加載來判斷的,如果能找到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
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 {
//......
}
從類路徑看,是在jdk.management的模塊里頭,所在包為com.sun.management。如果要是的metrics能有jvm.gc.concurrent.phase.time以及jvm.gc.pause的timer指標(biāo)的話,則要求jdk里頭有com.sun.management.GarbageCollectionNotificationInfo,默認(rèn)是有的,如果你的jdk進(jìn)行了jlink的話,則需要加上java.management以及jdk.management
java.management與jdk.management
management相關(guān)的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
可以看到j(luò)ava.management模塊qualified exports sun.management to jdk.jconsole jdk.management jdk.management.agent,注意這里是sun.management
這個mod提供了jmx相關(guān)類庫,不加的話,依賴jxm的功能會報錯,比如
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
可以看到j(luò)dk.management導(dǎo)出了com.sun.management,注意這里是com.sun.management
小結(jié)
要想在metrics里頭有jvm.gc.concurrent.phase.time以及jvm.gc.pause的timer指標(biāo),則需要添加jdk.management模塊,GarbageCollectionNotificationInfo是在com.sun.management包里頭,而不是sun.management包。JvmGcMetrics用到了jmx,因此也需要加上java.lang.management模塊。