聊聊JvmGcMetrics的managementExtensionsPresent

本文主要研究下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指标

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指标的话,则要求jdk里头有com.sun.management.GarbageCollectionNotificationInfo,默认是有的,如果你的jdk进行了jlink的话,则需要加上java.management以及jdk.management

java.management与jdk.management

management相关的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

可以看到java.management模块qualified exports sun.management to jdk.jconsole jdk.management jdk.management.agent,注意这里是sun.management

这个mod提供了jmx相关类库,不加的话,依赖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

可以看到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模块。

doc

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 202,980评论 5 476
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 85,178评论 2 380
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 149,868评论 0 336
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,498评论 1 273
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,492评论 5 364
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,521评论 1 281
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,910评论 3 395
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,569评论 0 256
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,793评论 1 296
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,559评论 2 319
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,639评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,342评论 4 318
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,931评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,904评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,144评论 1 259
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,833评论 2 349
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,350评论 2 342

推荐阅读更多精彩内容

  • /Library/Java/JavaVirtualMachines/jdk-9.jdk/Contents/Home...
    光剑书架上的书阅读 3,847评论 2 8
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,580评论 18 139
  • 转载blog.csdn.net/ning109314/article/details/10411495/ JVM工...
    forever_smile阅读 5,350评论 1 56
  • 【一】 那栋楼,599号,曾有一对恋人在那里殉情,流言吓心,岁月几转,租客依然很少。 夜色暗冷,深夜1点,她从59...
    只会用笔思考的人阅读 339评论 0 2
  • 眼睁睁看着自己的身体崩溃还要怎样,我又能怎样,吃了TMD六天中药病情一直在恶化。一天比一天痒,这两天基本上都是凌晨...
    天蓝的新灵阅读 211评论 3 0