默认情况下,Netty 使用ByteBufAllocator.DEFAULT
(实际上是ByteBufUtil.DEFAULT_ALLOCATOR
or UnpooledByteBufAllocator.DEFAULT
)PooledByteBufAllocator.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 分配器UnpooledByteBufAllocator
,PooledByteBufAllocator
实现ByteBufAllocatorMetricProvider
提供 2 种方法:
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 来获取总引用计数。