如何获取Netty 4应用程序的直接内存快照

问题描述 投票:1回答:1

我有一个基于Netty的服务器,它可以异步处理大量的HTTP请求。

目标 - 公开应用程序的直接内存使用。

现在我明白引用计数是暴露内存的一种方式。但是对于每个请求,很少有对象(如httpContent等)被显式保留,而对于其他对象,Netty会在内部更新引用计数。

  1. 由于服务器一次能够处理大量请求,我如何监控应用程序的直接内存使用情况并将其公开?
  2. 有没有办法在整个应用程序中获取总引用计数?
  3. 除了ReferenceCount之外,还有哪些监控直接内存使用的方法?
java memory netty reference-counting directmemory
1个回答
1
投票

Netty默认使用ByteBufAllocator.DEFAULT(实际上是ByteBufUtil.DEFAULT_ALLOCATORUnpooledByteBufAllocator.DEFAULTPooledByteBufAllocator.DEFAULT)分配器。如果您没有在代码中明确设置另一个分配器,则可以使用它来跟踪内存消耗。

您可以使用下一个代码执行此操作:

public class MemoryStat {

    public final long heapBytes;

    public final long directBytes;

    public MemoryStat(ByteBufAllocator byteBufAllocator) {
        long directMemory = 0;
        long heapMemory = 0;

        if (byteBufAllocator instanceof ByteBufAllocatorMetricProvider) {
            ByteBufAllocatorMetric metric = ((ByteBufAllocatorMetricProvider) byteBufAllocator).metric();
            directMemory = metric.usedDirectMemory();
            heapMemory = metric.usedHeapMemory();
        }

        this.directBytes = directMemory;
        this.heapBytes = heapMemory;
    }
}

用法:new MemoryStat(ByteBufAllocator.DEFAULT);

两个默认的netty分配器UnpooledByteBufAllocatorPooledByteBufAllocator都实现了ByteBufAllocatorMetricProvider,它提供了两种方法:

public interface ByteBufAllocatorMetric {
    /**
     * Returns the number of bytes of heap memory used by a {@link ByteBufAllocator} or {@code -1} if unknown.
     */
    long usedHeapMemory();

    /**
     * Returns the number of bytes of direct memory used by a {@link ByteBufAllocator} or {@code -1} if unknown.
     */
    long usedDirectMemory();
}

没有直接API来获取总引用计数。

© www.soinside.com 2019 - 2024. All rights reserved.