[Netty源碼分析]ByteBuf(五)

ByteBuf的釋放

//AbstractReferenceCountedByteBuf
@Override
public final boolean release() {
    for (;;) {
        int refCnt = this.refCnt;
        if (refCnt == 0) {
            throw new IllegalReferenceCountException(0, -1);
        }
        if (refCntUpdater.compareAndSet(this, refCnt, refCnt - 1)) {//判斷ByteBuf是否被引用
            if (refCnt == 1) {
                deallocate();
                return true;
            }
            return false;
        }
    }
}
↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓
//PooledByteBuf
@Override
protected final void deallocate() {
    if (handle >= 0) {
        final long handle = this.handle;
        this.handle = -1;//使PooledByteBuf不指向任何一塊內存
        memory = null;
        tmpNioBuf = null;
        chunk.arena.free(chunk, handle, maxLength, cache);//釋放內存
        chunk = null;
        recycle();//回收對象,加到對象池
    }
}
↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓
//PooledArena
1. 連續(xù)的內存區(qū)段加到緩存
void free(PoolChunk<T> chunk, long handle, int normCapacity, PoolThreadCache cache) {
    if (chunk.unpooled) {
        int size = chunk.chunkSize();
        destroyChunk(chunk);
        activeBytesHuge.add(-size);
        deallocationsHuge.increment();
    } else {
        SizeClass sizeClass = sizeClass(normCapacity);
        if (cache != null && cache.add(this, chunk, handle, normCapacity, sizeClass)) {
            // cached so not free it.
            return;
        }
        freeChunk(chunk, handle, sizeClass);
    }
}
↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓
//PooledThreadCache
boolean add(PoolArena<?> area, PoolChunk chunk, long handle, int normCapacity, SizeClass sizeClass) {
    MemoryRegionCache<?> cache = cache(area, normCapacity, sizeClass);
    if (cache == null) {
        return false;
    }
    return cache.add(chunk, handle);
}
↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓
//PooledThreadCache
private MemoryRegionCache<?> cache(PoolArena<?> area, int normCapacity, SizeClass sizeClass) {
    //拿到第幾個cache進行返回
    switch (sizeClass) {
      case Normal:
          return cacheForNormal(area, normCapacity);
      case Small:
          return cacheForSmall(area, normCapacity);
      case Tiny:
          return cacheForTiny(area, normCapacity);
      default:
          throw new Error();
    }
}
↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓
//PooledThreadCache
private static <T> MemoryRegionCache<T> cache(MemoryRegionCache<T>[] cache, int idx) {
    if (cache == null || idx > cache.length - 1) {
        return null;
    }
    return cache[idx];
}
↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓
//PooledThreadCache
public final boolean add(PoolChunk<T> chunk, long handle) {
    Entry<T> entry = newEntry(chunk, handle);
    boolean queued = queue.offer(entry);
    if (!queued) {
        // If it was not possible to cache the chunk, immediately recycle the entry
        entry.recycle();
    }
    return queued;
 }
2. 標志連續(xù)的內存區(qū)段為未使用(無法加入cache情況下)
//PoolArena
void freeChunk(PoolChunk<T> chunk, long handle, SizeClass sizeClass) {
    final boolean destroyChunk;
    synchronized (this) {
        switch (sizeClass) {
          case Normal:
              ++deallocationsNormal;
              break;
          case Small:
              ++deallocationsSmall;
              break;
          case Tiny:
              ++deallocationsTiny;
              break;
          default:
              throw new Error();
        }
        destroyChunk = !chunk.parent.free(chunk, handle);
    }
    if (destroyChunk) {
        // destroyChunk not need to be called while holding the synchronized lock.
        destroyChunk(chunk);
    }
}
//PoolChunkList
private boolean move(PoolChunk<T> chunk) {
    assert chunk.usage() < maxUsage;
    if (chunk.usage() < minUsage) {
        // Move the PoolChunk down the PoolChunkList linked-list.
        return move0(chunk);
    }
    // PoolChunk fits into this PoolChunkList, adding it here.
    add0(chunk);
    return true;
}
↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓
//PoolChunk
/**
     * Free a subpage or a run of pages
     * When a subpage is freed from PoolSubpage, it might be added back to subpage pool of the owning PoolArena
     * If the subpage pool in PoolArena has at least one other PoolSubpage of given elemSize, we can
     * completely free the owning Page so it is available for subsequent allocations
     *
     * @param handle handle to free
     */
void free(long handle) {
    int memoryMapIdx = memoryMapIdx(handle);
    int bitmapIdx = bitmapIdx(handle);
    if (bitmapIdx != 0) { // free a subpage
        PoolSubpage<T> subpage = subpages[subpageIdx(memoryMapIdx)];
        assert subpage != null && subpage.doNotDestroy;
        // Obtain the head of the PoolSubPage pool that is owned by the PoolArena and synchronize on it.
        // This is need as we may add it back and so alter the linked-list structure.
        PoolSubpage<T> head = arena.findSubpagePoolHead(subpage.elemSize);
        synchronized (head) {
            if (subpage.free(head, bitmapIdx & 0x3FFFFFFF)) {
                return;
            }
        }
    }
    freeBytes += runLength(memoryMapIdx);
    setValue(memoryMapIdx, depth(memoryMapIdx));
    updateParentsFree(memoryMapIdx);
 }
3. 回收對象到對象池
//PoolByteBuf
private void recycle() {
    recyclerHandle.recycle(this);
}
↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓
//Recycler$DefaultHandle
//回收到handle的stack中
@Override
public void recycle(Object object) {
    if (object != value) {
        throw new IllegalArgumentException("object does not belong to handle");
    }
    stack.push(this);
}
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
  • 序言:七十年代末勒魔,一起剝皮案震驚了整個濱河市舞终,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖培慌,帶你破解...
    沈念sama閱讀 217,406評論 6 503
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異呼畸,居然都是意外死亡鸳兽,警方通過查閱死者的電腦和手機,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,732評論 3 393
  • 文/潘曉璐 我一進店門品擎,熙熙樓的掌柜王于貴愁眉苦臉地迎上來埋合,“玉大人,你說我怎么就攤上這事萄传∩跛蹋” “怎么了?”我有些...
    開封第一講書人閱讀 163,711評論 0 353
  • 文/不壞的土叔 我叫張陵,是天一觀的道長振诬。 經(jīng)常有香客問我蹭睡,道長,這世上最難降的妖魔是什么赶么? 我笑而不...
    開封第一講書人閱讀 58,380評論 1 293
  • 正文 為了忘掉前任肩豁,我火速辦了婚禮,結果婚禮上辫呻,老公的妹妹穿的比我還像新娘清钥。我一直安慰自己,他們只是感情好放闺,可當我...
    茶點故事閱讀 67,432評論 6 392
  • 文/花漫 我一把揭開白布祟昭。 她就那樣靜靜地躺著,像睡著了一般雄人。 火紅的嫁衣襯著肌膚如雪从橘。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,301評論 1 301
  • 那天础钠,我揣著相機與錄音恰力,去河邊找鬼。 笑死旗吁,一個胖子當著我的面吹牛踩萎,可吹牛的內容都是我干的。 我是一名探鬼主播很钓,決...
    沈念sama閱讀 40,145評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼香府,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了码倦?” 一聲冷哼從身側響起企孩,我...
    開封第一講書人閱讀 39,008評論 0 276
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎袁稽,沒想到半個月后勿璃,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,443評論 1 314
  • 正文 獨居荒郊野嶺守林人離奇死亡推汽,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 37,649評論 3 334
  • 正文 我和宋清朗相戀三年补疑,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片歹撒。...
    茶點故事閱讀 39,795評論 1 347
  • 序言:一個原本活蹦亂跳的男人離奇死亡莲组,死狀恐怖,靈堂內的尸體忽然破棺而出暖夭,到底是詐尸還是另有隱情锹杈,我是刑警寧澤撵孤,帶...
    沈念sama閱讀 35,501評論 5 345
  • 正文 年R本政府宣布,位于F島的核電站嬉橙,受9級特大地震影響早直,放射性物質發(fā)生泄漏。R本人自食惡果不足惜市框,卻給世界環(huán)境...
    茶點故事閱讀 41,119評論 3 328
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望糕韧。 院中可真熱鬧枫振,春花似錦、人聲如沸萤彩。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,731評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽雀扶。三九已至杖小,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間愚墓,已是汗流浹背予权。 一陣腳步聲響...
    開封第一講書人閱讀 32,865評論 1 269
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留浪册,地道東北人扫腺。 一個月前我還...
    沈念sama閱讀 47,899評論 2 370
  • 正文 我出身青樓,卻偏偏與公主長得像村象,于是被迫代替她去往敵國和親笆环。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 44,724評論 2 354

推薦閱讀更多精彩內容