你能在 Java 中获得基本的 GC 统计信息吗? [英] Can you get basic GC stats in Java?

查看:28
本文介绍了你能在 Java 中获得基本的 GC 统计信息吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想让一些长时间运行的服务器应用程序定期输出 Java 中的一般 GC 性能数字,比如 Runtime.freeMemory() 等 GC 等值.比如完成的周期数、平均时间等.

I would like to have some long-running server applications periodically output general GC performance numbers in Java, something like the GC equivalent of Runtime.freeMemory(), etc. Something like number of cycles done, average time, etc.

我们的系统在客户机器上运行,怀疑配置错误的内存池会导致过多的 GC 频率和长度 - 我认为定期报告基本 GC 活动通常是好的.

We have systems running on customer machines where there is a suspicion that misconfigured memory pools are causing excessive GC frequency and length - it occurs to me that it would be good in general to periodically report the basic GC activity.

是否有任何独立于平台的方式来做到这一点?

Is there any platform independent way to do this?

我特别想在运行时将此数据输出到系统日志(控制台);这不是我想连接到 JVM 的东西,就像 JConsole 或 JVisualVM 一样.

Edit2:MX bean 看起来像我想要的 - 有没有人有一个获得其中之一的工作代码示例?

The MX bean looks like what I want - does anyone have a working code example which obtains one of these?

推荐答案

这是一个使用 GarbageCollectorMXBean 打印出 GC 统计信息.大概您会定期调用此方法,例如使用 ScheduledExecutorService 进行调度.

Here's an example using GarbageCollectorMXBean to print out GC stats. Presumably you would call this method periodically, e.g. scheduling using a ScheduledExecutorService.

public void printGCStats() {
    long totalGarbageCollections = 0;
    long garbageCollectionTime = 0;

    for(GarbageCollectorMXBean gc :
            ManagementFactory.getGarbageCollectorMXBeans()) {

        long count = gc.getCollectionCount();

        if(count >= 0) {
            totalGarbageCollections += count;
        }

        long time = gc.getCollectionTime();

        if(time >= 0) {
            garbageCollectionTime += time;
        }
    }

    System.out.println("Total Garbage Collections: "
        + totalGarbageCollections);
    System.out.println("Total Garbage Collection Time (ms): "
        + garbageCollectionTime);
}

这篇关于你能在 Java 中获得基本的 GC 统计信息吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆