netty源碼分析(27)- UnpooledByteBufAllocator分析

上一節(jié)查看了ByteBufAllocator,并了解了其抽象實(shí)現(xiàn),和一些根據(jù)不同的內(nèi)存類型進(jìn)行內(nèi)存分配的思路。

本節(jié)研究UnpooledByteBufAllocator,包括heapdirect的內(nèi)存分配闷畸,以及Unsafe非unsafe的區(qū)別。

關(guān)于heap內(nèi)存的分配
  • 入口
    @Override
    protected ByteBuf newHeapBuffer(int initialCapacity, int maxCapacity) {
        //判斷是有unsafe來(lái)分配
        return PlatformDependent.hasUnsafe() ?
                new InstrumentedUnpooledUnsafeHeapByteBuf(this, initialCapacity, maxCapacity) :
                new InstrumentedUnpooledHeapByteBuf(this, initialCapacity, maxCapacity);
    }
  • 查看new InstrumentedUnpooledUnsafeHeapByteBuf(this, initialCapacity, maxCapacity) :
    發(fā)現(xiàn)分配Unpooled吞滞、Unsafe佑菩、Heap內(nèi)存,其實(shí)是分配了一個(gè)byte數(shù)組裁赠,并保存在UnpooledHeapByteBuf#array成員變量中殿漠。該內(nèi)存的初始值容量和最大可擴(kuò)展容量可以指定。
    InstrumentedUnpooledUnsafeHeapByteBuf(UnpooledByteBufAllocator alloc, int initialCapacity, int maxCapacity) {
            super(alloc, initialCapacity, maxCapacity);
    }

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

    public UnpooledHeapByteBuf(ByteBufAllocator alloc, int initialCapacity, int maxCapacity) {
        super(maxCapacity);

        checkNotNull(alloc, "alloc");

        if (initialCapacity > maxCapacity) {
            throw new IllegalArgumentException(String.format(
                    "initialCapacity(%d) > maxCapacity(%d)", initialCapacity, maxCapacity));
        }

        this.alloc = alloc;
        //設(shè)置array
        setArray(allocateArray(initialCapacity));
        //設(shè)置readerIndex和writerIndex指針初始值為0
        setIndex(0, 0);
    }

    protected byte[] allocateArray(int initialCapacity) {
        //初始化了一個(gè)新的byte數(shù)組
        return new byte[initialCapacity];
    }

    private void setArray(byte[] initialArray) {
        //保存數(shù)組
        array = initialArray;
        tmpNioBuf = null;
    }

    @Override
    public ByteBuf setIndex(int readerIndex, int writerIndex) {
        if (checkBounds) {
            checkIndexBounds(readerIndex, writerIndex, capacity());
        }
        //設(shè)置
        setIndex0(readerIndex, writerIndex);
        return this;
    }

    final void setIndex0(int readerIndex, int writerIndex) {
        //設(shè)置讀寫指針
        this.readerIndex = readerIndex;
        this.writerIndex = writerIndex;
    }

  • 查看new InstrumentedUnpooledHeapByteBuf(this, initialCapacity, maxCapacity);內(nèi)存分配佩捞,其實(shí)例化過(guò)成和InstrumentedUnpooledUnsafeHeapByteBuf一樣绞幌。在這里看不出safeunsafe的區(qū)別,經(jīng)過(guò)之前的代碼一忱,可以重獲取的時(shí)候 getByte方法進(jìn)入查看.
    InstrumentedUnpooledHeapByteBuf(UnpooledByteBufAllocator alloc, int initialCapacity, int maxCapacity) {
            super(alloc, initialCapacity, maxCapacity);
    }


    public UnpooledHeapByteBuf(ByteBufAllocator alloc, int initialCapacity, int maxCapacity) {
        super(maxCapacity);

        checkNotNull(alloc, "alloc");

        if (initialCapacity > maxCapacity) {
            throw new IllegalArgumentException(String.format(
                    "initialCapacity(%d) > maxCapacity(%d)", initialCapacity, maxCapacity));
        }

        this.alloc = alloc;
        //設(shè)置array
        setArray(allocateArray(initialCapacity));
        //設(shè)置readerIndex和writerIndex指針初始值為0
        setIndex(0, 0);
    }

  • 查看UnpooledHeapByteBuf#getByte()方法莲蜘,堆內(nèi)存類型的ByteBuf獲取的時(shí)候。直接通過(guò)下標(biāo)獲取byte數(shù)組中的byte
    @Override
    public byte getByte(int index) {
        ensureAccessible();
        return _getByte(index);
    }

   @Override
    protected byte _getByte(int index) {
        //該array為初始化的時(shí)候帘营,實(shí)例化的byte[]
        return HeapByteBufUtil.getByte(array, index);
    }

    static byte getByte(byte[] memory, int index) {
        //直接拿到一個(gè)數(shù)組
        return memory[index];
    }
  • 查看UnpooledUnsafeHeapByteBuf#getByte()方法票渠,獲取byte字節(jié)的時(shí)候,調(diào)用的是jdk的UNSAFE對(duì)象芬迄。
    @Override
    public byte getByte(int index) {
        checkIndex(index);
        return _getByte(index);
    }

    @Override
    protected byte _getByte(int index) {
        return UnsafeByteBufUtil.getByte(array, index);
    }

    static byte getByte(byte[] array, int index) {
        return PlatformDependent.getByte(array, index);
    }

    public static byte getByte(byte[] data, int index) {
        return PlatformDependent0.getByte(data, index);
    }

    static byte getByte(byte[] data, int index) {
        //通過(guò)UNSAFE去獲取
        return UNSAFE.getByte(data, BYTE_ARRAY_BASE_OFFSET + index);
    }

關(guān)于direct內(nèi)存的分配
  • 入口UnpooledByteBufAllocator#newDirectBuffer()
    @Override
    protected ByteBuf newDirectBuffer(int initialCapacity, int maxCapacity) {
        final ByteBuf buf;
        //判斷是否有unsafe對(duì)象
        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);
    }
  • 跟蹤buf = new InstrumentedUnpooledDirectByteBuf(this, initialCapacity, maxCapacity);可以發(fā)現(xiàn)问顷,UnpooledDirect類型得內(nèi)存分配實(shí)際上是維護(hù)了一個(gè)底層jdk的一個(gè)DirectByteBuffer禀梳。分配內(nèi)存的時(shí)候就創(chuàng)建它杜窄,并將他保存到buffer成員變量。
    InstrumentedUnpooledDirectByteBuf(
            UnpooledByteBufAllocator alloc, int initialCapacity, int maxCapacity) {
        super(alloc, initialCapacity, maxCapacity);
    }  

    public UnpooledDirectByteBuf(ByteBufAllocator alloc, int initialCapacity, int maxCapacity) {
        super(maxCapacity);
        if (alloc == null) {
            throw new NullPointerException("alloc");
        }
        //檢查合法性
        checkPositiveOrZero(initialCapacity, "initialCapacity");
        checkPositiveOrZero(maxCapacity, "maxCapacity");
        if (initialCapacity > maxCapacity) {
            throw new IllegalArgumentException(String.format(
                    "initialCapacity(%d) > maxCapacity(%d)", initialCapacity, maxCapacity));
        }

        this.alloc = alloc;
        //獲取jdkDirectBuffer并保存到成員變量
        setByteBuffer(allocateDirect(initialCapacity));
    }

    private void setByteBuffer(ByteBuffer buffer) {
        ByteBuffer oldBuffer = this.buffer;
        //釋放舊的buffer
        if (oldBuffer != null) {
            if (doNotFree) {
                doNotFree = false;
            } else {
                freeDirect(oldBuffer);
            }
        }
        //保存新buffer
        this.buffer = buffer;
        tmpNioBuf = null;
        capacity = buffer.remaining();
    }


    protected ByteBuffer allocateDirect(int initialCapacity) {
        //分配
        return ByteBuffer.allocateDirect(initialCapacity);
    }

    public static ByteBuffer allocateDirect(int capacity) {
        return new DirectByteBuffer(capacity);
    }

跟蹤iUnpooledHeapByteBuf#_getByte()算途,就比較簡(jiǎn)單了塞耕,直接使用jdk的api獲取。

    @Override
    protected byte _getByte(int index) {
        //使用buffer
        return buffer.get(index);
    }
  • 跟蹤new InstrumentedUnpooledUnsafeDirectByteBuf(this, initialCapacity, maxCapacity);可以發(fā)現(xiàn)Unpooled郊艘、Unsafe荷科、Direct的內(nèi)存分配唯咬,和非Unsafe的區(qū)別在于它計(jì)算了一個(gè)內(nèi)存首地址并且保存起來(lái)纱注,在計(jì)算內(nèi)存首地址的時(shí)候是通過(guò)UNSAFE對(duì)象去獲取的。保存內(nèi)存首地址的好處是可以在獲取的時(shí)候直接通過(guò)計(jì)算下標(biāo)直接獲取胆胰。
        InstrumentedUnpooledUnsafeDirectByteBuf(
                UnpooledByteBufAllocator alloc, int initialCapacity, int maxCapacity) {
            super(alloc, initialCapacity, maxCapacity);
        }

    public UnpooledUnsafeDirectByteBuf(ByteBufAllocator alloc, int initialCapacity, int maxCapacity) {
        super(maxCapacity);
        if (alloc == null) {
            throw new NullPointerException("alloc");
        }
        checkPositiveOrZero(initialCapacity, "initialCapacity");
        checkPositiveOrZero(maxCapacity, "maxCapacity");
        if (initialCapacity > maxCapacity) {
            throw new IllegalArgumentException(String.format(
                    "initialCapacity(%d) > maxCapacity(%d)", initialCapacity, maxCapacity));
        }

        this.alloc = alloc;
        //分配jdk底層DirectByteBuffer狞贱,設(shè)置buffer
        setByteBuffer(allocateDirect(initialCapacity), false);
    }

    final void setByteBuffer(ByteBuffer buffer, boolean tryFree) {
        if (tryFree) {
            ByteBuffer oldBuffer = this.buffer;
            if (oldBuffer != null) {
                if (doNotFree) {
                    doNotFree = false;
                } else {
                    freeDirect(oldBuffer);
                }
            }
        }
        this.buffer = buffer;
        //計(jì)算內(nèi)存地址
        memoryAddress = PlatformDependent.directBufferAddress(buffer);
        tmpNioBuf = null;
        capacity = buffer.remaining();
    }

    public static long directBufferAddress(ByteBuffer buffer) {
        return PlatformDependent0.directBufferAddress(buffer);
    }

    static long directBufferAddress(ByteBuffer buffer) {
        return getLong(buffer, ADDRESS_FIELD_OFFSET);
    }

    private static long getLong(Object object, long fieldOffset) {
        //調(diào)用UNSAFE獲取內(nèi)存地址
        return UNSAFE.getLong(object, fieldOffset);
    }

跟蹤UnpooledUnsafeDirectByteBuf#_getByte(),可以知道UNSAFE的直接內(nèi)存內(nèi)容獲取方式是通過(guò)內(nèi)存首地址 + 偏移量獲取的蜀涨。

    @Override
    protected byte _getByte(int index) {
        //通過(guò)計(jì)算地址獲取
        return UnsafeByteBufUtil.getByte(addr(index));
    }

    long addr(int index) {
        //直接從 內(nèi)存首地址 + 偏移量 獲取
        return memoryAddress + index;
    }

    static byte getByte(long address) {
        //address正是memoryAddress + index
        return UNSAFE.getByte(address);
    }
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末瞎嬉,一起剝皮案震驚了整個(gè)濱河市蝎毡,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌氧枣,老刑警劉巖沐兵,帶你破解...
    沈念sama閱讀 218,036評(píng)論 6 506
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場(chǎng)離奇詭異便监,居然都是意外死亡扎谎,警方通過(guò)查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,046評(píng)論 3 395
  • 文/潘曉璐 我一進(jìn)店門烧董,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái)毁靶,“玉大人,你說(shuō)我怎么就攤上這事逊移≡み海” “怎么了?”我有些...
    開封第一講書人閱讀 164,411評(píng)論 0 354
  • 文/不壞的土叔 我叫張陵胳泉,是天一觀的道長(zhǎng)拐叉。 經(jīng)常有香客問(wèn)我,道長(zhǎng)胶背,這世上最難降的妖魔是什么巷嚣? 我笑而不...
    開封第一講書人閱讀 58,622評(píng)論 1 293
  • 正文 為了忘掉前任,我火速辦了婚禮钳吟,結(jié)果婚禮上怪嫌,老公的妹妹穿的比我還像新娘。我一直安慰自己就乓,他們只是感情好片部,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,661評(píng)論 6 392
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著暇番,像睡著了一般嗤放。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上壁酬,一...
    開封第一講書人閱讀 51,521評(píng)論 1 304
  • 那天次酌,我揣著相機(jī)與錄音,去河邊找鬼舆乔。 笑死岳服,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的希俩。 我是一名探鬼主播吊宋,決...
    沈念sama閱讀 40,288評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼颜武!你這毒婦竟也來(lái)了璃搜?” 一聲冷哼從身側(cè)響起拖吼,我...
    開封第一講書人閱讀 39,200評(píng)論 0 276
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤,失蹤者是張志新(化名)和其女友劉穎这吻,沒(méi)想到半個(gè)月后吊档,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,644評(píng)論 1 314
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡唾糯,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,837評(píng)論 3 336
  • 正文 我和宋清朗相戀三年籍铁,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片趾断。...
    茶點(diǎn)故事閱讀 39,953評(píng)論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡拒名,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出芋酌,到底是詐尸還是另有隱情增显,我是刑警寧澤,帶...
    沈念sama閱讀 35,673評(píng)論 5 346
  • 正文 年R本政府宣布脐帝,位于F島的核電站同云,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏堵腹。R本人自食惡果不足惜炸站,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,281評(píng)論 3 329
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望疚顷。 院中可真熱鬧旱易,春花似錦、人聲如沸腿堤。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,889評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)笆檀。三九已至忌堂,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間酗洒,已是汗流浹背士修。 一陣腳步聲響...
    開封第一講書人閱讀 33,011評(píng)論 1 269
  • 我被黑心中介騙來(lái)泰國(guó)打工, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留樱衷,地道東北人棋嘲。 一個(gè)月前我還...
    沈念sama閱讀 48,119評(píng)論 3 370
  • 正文 我出身青樓,卻偏偏與公主長(zhǎng)得像箫老,于是被迫代替她去往敵國(guó)和親封字。 傳聞我的和親對(duì)象是個(gè)殘疾皇子黔州,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,901評(píng)論 2 355

推薦閱讀更多精彩內(nèi)容