Java 获取垃圾回收队列长度

Java About 901 words

反射获取

Java 8及之前可以使用反射,获取Finalizer中的queue字段,然后获取长度。

Java 9模块化之后不可用。

try {
    Class<?> finalizerClass = Class.forName("java.lang.ref.Finalizer");
    Field queueStaticField = finalizerClass.getDeclaredField("queue");
    queueStaticField.setAccessible(true);
    ReferenceQueue<Object> referenceQueue = (ReferenceQueue) queueStaticField.get(null);

    Field queueLengthField = ReferenceQueue.class.getDeclaredField("queueLength");
    queueLengthField.setAccessible(true);
    long queueLength = (long) queueLengthField.get(referenceQueue);
    System.out.format(LocalDateTime.now() + " There are %d references in the queue---%d%n", queueLength, ManagementFactory.getMemoryMXBean().getObjectPendingFinalizationCount());
} catch (Exception e) {
    e.printStackTrace();
}

MXBean

使用Management Extension Bean获取待回收对象的个数。

ManagementFactory.getMemoryMXBean().getObjectPendingFinalizationCount()
Views: 672 · Posted: 2023-06-20

————        END        ————

Give me a Star, Thanks:)

https://github.com/fendoudebb/LiteNote

扫描下方二维码关注公众号和小程序↓↓↓

扫描下方二维码关注公众号和小程序↓↓↓


Today On History
Browsing Refresh