Netty по умолчанию использует ByteBufAllocator.DEFAULT
(то есть на самом деле ByteBufUtil.DEFAULT_ALLOCATOR
, то есть 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 для получения общего количества ссылок.