欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

java代码中获取full gc、young gc情况

程序员文章站 2022-05-06 21:21:13
...

对于大型的高并发服务,我们可能需要定时或实时获取进程的gc情况,很荣幸,java给我们提供了现成的方法。

    private static void reportGC(ReportAPI reporter) {
        long fullCount = 0, fullTime = 0, youngCount = 0, youngTime = 0;
        List<GarbageCollectorMXBean> gcs = ManagementFactory.getGarbageCollectorMXBeans();
        for (GarbageCollectorMXBean gc : gcs) {
            switch (GarbageCollectorName.of(gc.getName())) {
                case MarkSweepCompact:
                case PSMarkSweep:
                case ConcurrentMarkSweep:
                    fullCount += gc.getCollectionCount();
                    fullTime += gc.getCollectionTime();
                    break;
                case Copy:
                case ParNew:
                case PSScavenge:
                    youngCount += gc.getCollectionCount();
                    youngTime += gc.getCollectionTime();
                    break;
            }
            //todo your deal code, perfcounter report or write log here
        }

getGarbageCollectorMXBeans可以获取JVM中不同的对象列表,从中找出我们的jvm.properties中配置使用的gc方法,分别进行统计次数及时间即可。

    /**
     * Returns a list of {@link GarbageCollectorMXBean} objects
     * in the Java virtual machine.
     * The Java virtual machine may have one or more
     * <tt>GarbageCollectorMXBean</tt> objects.
     * It may add or remove <tt>GarbageCollectorMXBean</tt>
     * during execution.
     *
     * @return a list of <tt>GarbageCollectorMXBean</tt> objects.
     *
     */
    public static List<GarbageCollectorMXBean> getGarbageCollectorMXBeans() {
        return ManagementFactoryHelper.getGarbageCollectorMXBeans();
    }

拿到full gc时间、次数及young gc时间及次数,进行后续的具体分析就可以了。