Nettyのバッファー(4)ByteBufAllocator

これは、ByteBufAllocatorの最後のサブクラスである、UnpooledByteBufAllocator、ByteBufアロケータ、メモリプールに基づいていないものを調べます。
ByteBufAllocatorMetricProviderでは、ByteBufAllocatorMetricプロバイダーインターフェイスを使用して、ByteBufのヒープとダイレクトのメモリ使用量を監視します。

public interface ByteBufAllocatorMetricProvider {

    /**
     * Returns a {@link ByteBufAllocatorMetric} for a {@link ByteBufAllocator}.
     */
    ByteBufAllocatorMetric metric();

}

ByteBufAllocatorMetric:

public interface ByteBufAllocatorMetric {

    /**
     * Returns the number of bytes of heap memory used by a {@link ByteBufAllocator} or {@code -1} if unknown.
     *
     * 已使用 Heap 占用内存大小
     */
    long usedHeapMemory();

    /**
     * Returns the number of bytes of direct memory used by a {@link ByteBufAllocator} or {@code -1} if unknown.
     *
     * 已使用 Direct 占用内存大小
     */
    long usedDirectMemory();

}

UnpooledByteBufAllocatorMetricは、UnpooledByteBufAllocatorの内部静的クラスで、ByteBufAllocatorMetricインターフェイス、UnpooledByteBufAllocatorMetric実装クラスを実装します。

/**
 * Direct ByteBuf 占用内存大小
 */
final LongCounter directCounter = PlatformDependent.newLongCounter();
/**
 * Heap ByteBuf 占用内存大小
 */
final LongCounter heapCounter = PlatformDependent.newLongCounter();

@Override
public long usedHeapMemory() {
    return heapCounter.value();
}

@Override
public long usedDirectMemory() {
    return directCounter.value();
}

2つのカウンター:
PlatformDependent#newLongCounter()メソッド、LongCounterオブジェクトを取得:

/**
 * Creates a new fastest {@link LongCounter} implementation for the current platform.
 */
public static LongCounter newLongCounter() {
    if (javaVersion() >= 8) {
        return new LongAdderCounter();
    } else {
        return new AtomicLongCounter();
    }
}

JDKバージョンによると、JDK> = 8はjava.util.concurrent.atomic.LongAdderを使用し、JDK <7はjava.util.concurrent.atomic.AtomicLongを使用します。

UnpooledByteBufAllocatorは、ByteBufAllocatorMetricProviderインターフェイスを実装し、メモリプールに基づいていない、一般的なByteBufアロケータであるAbstractByteBufAllocator抽象クラスを継承します。
建設:

/**
 * Metric
 */
private final UnpooledByteBufAllocatorMetric metric = new UnpooledByteBufAllocatorMetric();
/**
 * 是否禁用内存泄露检测功能,disableLeakDetector
 */
private final boolean disableLeakDetector;
/**
 * 不使用 `io.netty.util.internal.Cleaner` 释放 Direct ByteBuf
 *
 * @see UnpooledUnsafeNoCleanerDirectByteBuf
 * @see InstrumentedUnpooledUnsafeNoCleanerDirectByteBuf
 */
private final boolean noCleaner;

public UnpooledByteBufAllocator(boolean preferDirect) {
    this(preferDirect, false);
}

public UnpooledByteBufAllocator(boolean preferDirect, boolean disableLeakDetector) {
    this(preferDirect, disableLeakDetector, PlatformDependent.useDirectBufferNoCleaner() /** 返回 true **/ );
}

/**
 * Create a new instance
 *
 * @param preferDirect {@code true} if {@link #buffer(int)} should try to allocate a direct buffer rather than
 *                     a heap buffer
 * @param disableLeakDetector {@code true} if the leak-detection should be disabled completely for this
 *                            allocator. This can be useful if the user just want to depend on the GC to handle
 *                            direct buffers when not explicit released.
 * @param tryNoCleaner {@code true} if we should try to use {@link PlatformDependent#allocateDirectNoCleaner(int)}
 *                            to allocate direct memory.
 */
public UnpooledByteBufAllocator(boolean preferDirect, boolean disableLeakDetector, boolean tryNoCleaner) {
    super(preferDirect);
    this.disableLeakDetector = disableLeakDetector;
    noCleaner = tryNoCleaner && PlatformDependent.hasUnsafe() /** 返回 true **/
            && PlatformDependent.hasDirectBufferNoCleanerConstructor() /** 返回 true **/ ;
}

newHeapBuffer:

@Override
protected ByteBuf newHeapBuffer(int initialCapacity, int maxCapacity) {
    return PlatformDependent.hasUnsafe() ?
            new InstrumentedUnpooledUnsafeHeapByteBuf(this, initialCapacity, maxCapacity) :
            new InstrumentedUnpooledHeapByteBuf(this, initialCapacity, maxCapacity);
}

newDirectBuffer:

@Override
protected ByteBuf newDirectBuffer(int initialCapacity, int maxCapacity) {
    final ByteBuf buf;
    if (PlatformDependent.hasUnsafe()) {
        buf = noCleaner ? new InstrumentedUnpooledUnsafeNoCleanerDirectByteBuf(this, initialCapacity, maxCapacity) :
                new InstrumentedUnpooledUnsafeDirectByteBuf(this, initialCapacity, maxCapacity);
    } else {
        buf = new InstrumentedUnpooledDirectByteBuf(this, initialCapacity, maxCapacity);
    }
    return disableLeakDetector ? buf : toLeakAwareBuffer(buf);
}

compositeHeapBuffer:

@Override
public CompositeByteBuf compositeHeapBuffer(int maxNumComponents) {
    CompositeByteBuf buf = new CompositeByteBuf(this, false, maxNumComponents);
    return disableLeakDetector ? buf : toLeakAwareBuffer(buf);
}

compositeDirectBuffer

@Override
public CompositeByteBuf compositeDirectBuffer(int maxNumComponents) {
    CompositeByteBuf buf = new CompositeByteBuf(this, true, maxNumComponents);
    return disableLeakDetector ? buf : toLeakAwareBuffer(buf);
}

isDirectBufferPooled:

@Override
public boolean isDirectBufferPooled() {
    return false;
}

メトリック関連の操作方法:

@Override
public ByteBufAllocatorMetric metric() {
    return metric;
}

void incrementDirect(int amount) { // 增加 Direct
    metric.directCounter.add(amount);
}
void decrementDirect(int amount) { // 减少 Direct
    metric.directCounter.add(-amount);
}

void incrementHeap(int amount) { // 增加 Heap
    metric.heapCounter.add(amount);
}
void decrementHeap(int amount) { // 减少 Heap
    metric.heapCounter.add(-amount);
}

InstrumentedUnpooledUnsafeHeapByteBufは、UnpooledByteBufAllocatorの内部静的クラスで、UnpooledUnsafeHeapByteBufクラスを継承します。
元のクラスに基づいて、対応するメトリックの増加および減少操作メソッドを呼び出して、ヒープが占めるメモリのサイズを記録します。

private static final class InstrumentedUnpooledUnsafeHeapByteBuf extends UnpooledUnsafeHeapByteBuf {

    InstrumentedUnpooledUnsafeHeapByteBuf(UnpooledByteBufAllocator alloc, int initialCapacity, int maxCapacity) {
        super(alloc, initialCapacity, maxCapacity);
    }

    @Override
    protected byte[] allocateArray(int initialCapacity) {
        byte[] bytes = super.allocateArray(initialCapacity);
        // Metric ++
        ((UnpooledByteBufAllocator) alloc()).incrementHeap(bytes.length);
        return bytes;
    }

    @Override
    protected void freeArray(byte[] array) {
        int length = array.length;
        super.freeArray(array);
        // Metric --
        ((UnpooledByteBufAllocator) alloc()).decrementHeap(length);
    }
}

UnpooledByteBufAllocatorの内部静的クラスのInstrumentedUnpooledHeapByteBufは、UnpooledHeapByteBufクラスを継承します。

private static final class InstrumentedUnpooledHeapByteBuf extends UnpooledHeapByteBuf {

    InstrumentedUnpooledHeapByteBuf(UnpooledByteBufAllocator alloc, int initialCapacity, int maxCapacity) {
        super(alloc, initialCapacity, maxCapacity);
    }

    @Override
    protected byte[] allocateArray(int initialCapacity) {
        byte[] bytes = super.allocateArray(initialCapacity);
        // Metric ++
        ((UnpooledByteBufAllocator) alloc()).incrementHeap(bytes.length);
        return bytes;
    }

    @Override
    protected void freeArray(byte[] array) {
        int length = array.length;
        super.freeArray(array);
        // Metric --
        ((UnpooledByteBufAllocator) alloc()).decrementHeap(length);
    }
//在原先的基础上,调用 Metric 相应的增减操作方法,得以记录 Heap 占用内存的大小。
}

UnpooledByteBufAllocatorの内部静的クラスのInstrumentedUnpooledUnsafeDirectByteBufは、UnpooledUnsafeDirectByteBufクラスを継承します。

private static final class InstrumentedUnpooledUnsafeDirectByteBuf extends UnpooledUnsafeDirectByteBuf {
    InstrumentedUnpooledUnsafeDirectByteBuf(
            UnpooledByteBufAllocator alloc, int initialCapacity, int maxCapacity) {
        super(alloc, initialCapacity, maxCapacity);
    }

    @Override
    protected ByteBuffer allocateDirect(int initialCapacity) {
        ByteBuffer buffer = super.allocateDirect(initialCapacity);
        // Metric ++
        ((UnpooledByteBufAllocator) alloc()).incrementDirect(buffer.capacity());
        return buffer;
    }

    @Override
    protected void freeDirect(ByteBuffer buffer) {
        int capacity = buffer.capacity();
        super.freeDirect(buffer);
        // Metric --
        ((UnpooledByteBufAllocator) alloc()).decrementDirect(capacity);
    }
}

UnpooledDirectByteBufクラスを継承するInstrumentedUnpooledDirectByteBufの内部静的クラス:

private static final class InstrumentedUnpooledDirectByteBuf extends UnpooledDirectByteBuf {

    InstrumentedUnpooledDirectByteBuf(
            UnpooledByteBufAllocator alloc, int initialCapacity, int maxCapacity) {
        super(alloc, initialCapacity, maxCapacity);
    }

    @Override
    protected ByteBuffer allocateDirect(int initialCapacity) {
        ByteBuffer buffer = super.allocateDirect(initialCapacity);
        // Metric ++
        ((UnpooledByteBufAllocator) alloc()).incrementDirect(buffer.capacity());
        return buffer;
    }

    @Override
    protected void freeDirect(ByteBuffer buffer) {
        int capacity = buffer.capacity();
        super.freeDirect(buffer);
        // Metric --
        ((UnpooledByteBufAllocator) alloc()).decrementDirect(capacity);
    }

}

UnpooledUnsafeNoCleanerDirectByteBufクラスを継承するInstrumentedUnpooledDirectByteBufの内部静的クラス:

private static final class InstrumentedUnpooledUnsafeNoCleanerDirectByteBuf
        extends UnpooledUnsafeNoCleanerDirectByteBuf {

    InstrumentedUnpooledUnsafeNoCleanerDirectByteBuf(
            UnpooledByteBufAllocator alloc, int initialCapacity, int maxCapacity) {
        super(alloc, initialCapacity, maxCapacity);
    }

    @Override
    protected ByteBuffer allocateDirect(int initialCapacity) {
        ByteBuffer buffer = super.allocateDirect(initialCapacity);
        // Metric ++
        ((UnpooledByteBufAllocator) alloc()).incrementDirect(buffer.capacity());
        return buffer;
    }

    @Override
    ByteBuffer reallocateDirect(ByteBuffer oldBuffer, int initialCapacity) {
        int capacity = oldBuffer.capacity();
        ByteBuffer buffer = super.reallocateDirect(oldBuffer, initialCapacity);
        // Metric ++
        ((UnpooledByteBufAllocator) alloc()).incrementDirect(buffer.capacity() - capacity);
        return buffer;
    }

    @Override
    protected void freeDirect(ByteBuffer buffer) {
        int capacity = buffer.capacity();
        super.freeDirect(buffer);
        // Metric --
        ((UnpooledByteBufAllocator) alloc()).decrementDirect(capacity);
    }

}

UnpooledUnsafeNoCleanerDirectByteBuf、UnpooledUnsafeDirectByteBufクラスを継承:

class UnpooledUnsafeNoCleanerDirectByteBuf extends UnpooledUnsafeDirectByteBuf {

    UnpooledUnsafeNoCleanerDirectByteBuf(ByteBufAllocator alloc, int initialCapacity, int maxCapacity) {
        super(alloc, initialCapacity, maxCapacity);
    }

    @Override
    protected ByteBuffer allocateDirect(int initialCapacity) {
        // 反射,直接创建 ByteBuffer 对象。并且该对象不带 Cleaner 对象
        return PlatformDependent.allocateDirectNoCleaner(initialCapacity);
    }

    ByteBuffer reallocateDirect(ByteBuffer oldBuffer, int initialCapacity) {
        return PlatformDependent.reallocateDirectNoCleaner(oldBuffer, initialCapacity);
    }

    @Override
    protected void freeDirect(ByteBuffer buffer) {
        // 直接释放 ByteBuffer 对象
        PlatformDependent.freeDirectNoCleaner(buffer);
    }

    @Override
    public ByteBuf capacity(int newCapacity) {
        checkNewCapacity(newCapacity);

        int oldCapacity = capacity();
        if (newCapacity == oldCapacity) {
            return this;
        }

        // 重新分配 ByteBuf 对象
        ByteBuffer newBuffer = reallocateDirect(buffer, newCapacity);

        if (newCapacity < oldCapacity) {
            if (readerIndex() < newCapacity) {
                // 重置 writerIndex 为 newCapacity ,避免越界
                if (writerIndex() > newCapacity) {
                    writerIndex(newCapacity);
                }
            } else {
                // 重置 writerIndex 和 readerIndex 为 newCapacity ,避免越界
                setIndex(newCapacity, newCapacity);
            }
        }

        // 设置 ByteBuf 对象
        setByteBuffer(newBuffer, false);
        return this;
    }

}
公開された46元の記事 ウォンの賞賛6 ビュー3847

おすすめ

転載: blog.csdn.net/weixin_43257196/article/details/105104906