Netty by default uses ByteBufAllocator.DEFAULT
(that is actually is ByteBufUtil.DEFAULT_ALLOCATOR
that is either UnpooledByteBufAllocator.DEFAULT
or PooledByteBufAllocator.DEFAULT
) allocator for the allocations. If you haven't explicitly set another allocator within your code you can use it to track your memory consumption.
You can do this with the next code:
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;
}
}
Usage: new MemoryStat(ByteBufAllocator.DEFAULT);
Both default netty allocators UnpooledByteBufAllocator
, PooledByteBufAllocator
implements ByteBufAllocatorMetricProvider
that provides 2 methods:
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();
}
There is no direct API to get total reference count.