netty源碼分析(26)- ByteBufAllocator分析

上一節簡單理解了以下ByteBuf的結構。詳細的api還需要自己奪取嘗試。

本節學些ByteBufAllocator,內存分配器(管理器)

  • 查看ByteBufAllocator,作爲頂層接口,它根據內存分配的類型定製了一些分配方法,主要還是根據是否是堆內存來進行分配。
    //根據具體的子類實現決定分配內存是direct還是head
    ByteBuf buffer();
    ByteBuf buffer(int var1);
    ByteBuf buffer(int var1, int var2);
    
    //分配一個是適用於IO的直接內存
    ByteBuf ioBuffer();
    ByteBuf ioBuffer(int var1);
    ByteBuf ioBuffer(int var1, int var2);
    
    //分配一塊head內存
    ByteBuf heapBuffer();
    ByteBuf heapBuffer(int var1);
    ByteBuf heapBuffer(int var1, int var2);
    
    //分配一塊direct內存
    ByteBuf directBuffer();
    ByteBuf directBuffer(int var1);
    ByteBuf directBuffer(int var1, int var2);
    
    //組合緩衝區
    CompositeByteBuf compositeBuffer();
    CompositeByteBuf compositeBuffer(int var1);
    CompositeByteBuf compositeHeapBuffer();
   
    CompositeByteBuf compositeHeapBuffer(int var1);
    CompositeByteBuf compositeDirectBuffer();
    CompositeByteBuf compositeDirectBuffer(int var1);

    boolean isDirectBufferPooled();
    int calculateNewCapacity(int var1, int var2);
  • AbstractByteBufAllocator是頂層接口ByteBufAllocator一個實現,作爲一個抽象的類,骨架。看一下他的buffer()方法。其實在AbstractByteBufAllocator層面是沒有定義Pooled和Unpooled以及Safe和Unsafe類別的內存分配,這一層只開放了一個抽象方法,具體的Pooled和Unpooled交由子類實現。
    @Override
    public ByteBuf buffer() {
        //是否是direct內存,調用具體不同的實現
        if (directByDefault) {
            //分配直接內存
            return directBuffer();
        }
        //分配對內存
        return heapBuffer();
    }

    @Override
    public ByteBuf directBuffer() {
        //參數:默認的容量256,最大容量Integer.MAX_VALUE;
        return directBuffer(DEFAULT_INITIAL_CAPACITY, DEFAULT_MAX_CAPACITY);
    }

    @Override
    public ByteBuf directBuffer(int initialCapacity, int maxCapacity) {
        //檢驗
        if (initialCapacity == 0 && maxCapacity == 0) {
            return emptyBuf;
        }
        //校驗參數設置是否正確
        validate(initialCapacity, maxCapacity);
        //創建DirectBuffer
        return newDirectBuffer(initialCapacity, maxCapacity);
    }

    /**
     * Create a direct {@link ByteBuf} with the given initialCapacity and maxCapacity.
     */
    protected abstract ByteBuf newDirectBuffer(int initialCapacity, int maxCapacity);

  • 關於Safe和Unsafe類別的內存分配,netty是根據jdk底層是否由封裝的unsafe來進行分配的,查看UnpooledByteBufAllocator#newHeapBuffer()
    @Override
    protected ByteBuf newHeapBuffer(int initialCapacity, int maxCapacity) {
        //判斷是有unsafe來分配
        return PlatformDependent.hasUnsafe() ?
                new InstrumentedUnpooledUnsafeHeapByteBuf(this, initialCapacity, maxCapacity) :
                new InstrumentedUnpooledHeapByteBuf(this, initialCapacity, maxCapacity);
    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章