Netty之Recycler

Recycler用來實現(xiàn)對象池搏熄,其中對應(yīng)堆內(nèi)存和直接內(nèi)存的池化實現(xiàn)分別是PooledHeapByteBuf和PooledDirectByteBuf速警。Recycler主要提供了3個方法:

  • get():獲取一個對象咧最。
  • recycle(T, Handle):回收一個對象后控,T為對象泛型扮碧。
  • newObject(Handle):當沒有可用對象時創(chuàng)建對象的實現(xiàn)方法白华。

Recycler的UML圖如下:

Recycler.png

Recycler關(guān)聯(lián)了4個核心類:

  • DefaultHandle:對象的包裝類走越,在Recycler中緩存的對象都會包裝成DefaultHandle類椭豫。
  • Stack:存儲本線程回收的對象。對象的獲取和回收對應(yīng)Stack的pop和push旨指,即獲取對象時從Stack中pop出1個DefaultHandle赏酥,回收對象時將對象包裝成DefaultHandle push到Stack中。Stack會與線程綁定谆构,即每個用到Recycler的線程都會擁有1個Stack裸扶,在該線程中獲取對象都是在該線程的Stack中pop出一個可用對象。
  • WeakOrderQueue:存儲其它線程回收到本線程stack的對象低淡,當某個線程從Stack中獲取不到對象時會從WeakOrderQueue中獲取對象姓言。每個線程的Stack擁有1個WeakOrderQueue鏈表,鏈表每個節(jié)點對應(yīng)1個其它線程的WeakOrderQueue蔗蹋,其它線程回收到該Stack的對象就存儲在這個WeakOrderQueue里何荚。
  • Link: WeakOrderQueue中包含1個Link鏈表,回收對象存儲在鏈表某個Link節(jié)點里猪杭,當Link節(jié)點存儲的回收對象滿了時會新建1個Link放在Link鏈表尾餐塘。

整個Recycler回收對象存儲結(jié)構(gòu)如下圖所示:


Recycler.png

下面分析下源碼,首先看下Recycler.recycle(T, Handle)方法皂吮,用于回收1個對象:

public final boolean recycle(T o, Handle handle) {
    if (handle == NOOP_HANDLE) {
        return false;
    }

    DefaultHandle h = (DefaultHandle) handle;
    if (h.stack.parent != this) {
        return false;
    }
    if (o != h.value) {
        throw new IllegalArgumentException("o does not belong to handle");
    }
    h.recycle();
    return true;
}

回收1個對象會調(diào)用該對象DefaultHandle.recycle()方法戒傻,如下:

 public void recycle() {
    stack.push(this);
 }

回收1個對象(DefaultHandle)就是把該對象push到stack中。

void push(DefaultHandle item) {
        Thread currentThread = Thread.currentThread();
        if (thread == currentThread) {
            // The current Thread is the thread that belongs to the Stack, we can try to push the object now.
            /**
             * 如果該stack就是本線程的stack蜂筹,那么直接把DefaultHandle放到該stack的數(shù)組里
             */
            pushNow(item);
        } else {
            // The current Thread is not the one that belongs to the Stack, we need to signal that the push
            // happens later.
            /**
             * 如果該stack不是本線程的stack需纳,那么把該DefaultHandle放到該stack的WeakOrderQueue中
             */
            pushLater(item, currentThread);
        }
    }

這里分為兩種情況,當stack是當前線程對應(yīng)的stack時艺挪,執(zhí)行pushNow(item)方法不翩,直接把對象放到該stack的DefaultHandle數(shù)組中,如下:

    /**
     * 直接把DefaultHandle放到stack的數(shù)組里,如果數(shù)組滿了那么擴展該數(shù)組為當前2倍大小
     * @param item
     */
    private void pushNow(DefaultHandle item) {
        if ((item.recycleId | item.lastRecycledId) != 0) {
            throw new IllegalStateException("recycled already");
        }
        item.recycleId = item.lastRecycledId = OWN_THREAD_ID;

        int size = this.size;
        if (size >= maxCapacity || dropHandle(item)) {
            // Hit the maximum capacity or should drop - drop the possibly youngest object.
            return;
        }
        if (size == elements.length) {
            elements = Arrays.copyOf(elements, min(size << 1, maxCapacity));
        }

        elements[size] = item;
        this.size = size + 1;
    }

當stack是其它線程的stack時口蝠,執(zhí)行pushLater(item, currentThread)方法器钟,將對象放到WeakOrderQueue中,如下:

private void pushLater(DefaultHandle item, Thread thread) {
       /** 
        * Recycler有1個stack->WeakOrderQueue映射妙蔗,每個stack會映射到1個WeakOrderQueue傲霸,這個WeakOrderQueue是該stack關(guān)聯(lián)的其它線程WeakOrderQueue鏈表的head WeakOrderQueue。
        * 當其它線程回收對象到該stack時會創(chuàng)建1個WeakOrderQueue中并加到stack的WeakOrderQueue鏈表中眉反。 
        */
        Map<Stack<?>, WeakOrderQueue> delayedRecycled = DELAYED_RECYCLED.get();
        WeakOrderQueue queue = delayedRecycled.get(this);
        if (queue == null) {
            /**
             * 如果delayedRecycled滿了那么將1個偽造的WeakOrderQueue(DUMMY)放到delayedRecycled中昙啄,并丟棄該對象(DefaultHandle)
             */
            if (delayedRecycled.size() >= maxDelayedQueues) {
                // Add a dummy queue so we know we should drop the object
                delayedRecycled.put(this, WeakOrderQueue.DUMMY);
                return;
            }
            // Check if we already reached the maximum number of delayed queues and if we can allocate at all.
            /**
             * 創(chuàng)建1個WeakOrderQueue
             */
            if ((queue = WeakOrderQueue.allocate(this, thread)) == null) {
                // drop object
                return;
            }
            delayedRecycled.put(this, queue);
        } else if (queue == WeakOrderQueue.DUMMY) {
            // drop object
            return;
        }

        /**
         * 將對象放入到該stack對應(yīng)的WeakOrderQueue中
         */
        queue.add(item);
    }


static WeakOrderQueue allocate(Stack<?> stack, Thread thread) {
        // We allocated a Link so reserve the space
        /**
         * 如果該stack的可用共享空間還能再容下1個WeakOrderQueue,那么創(chuàng)建1個WeakOrderQueue禁漓,否則返回null
         */
        return reserveSpace(stack.availableSharedCapacity, LINK_CAPACITY)
                ? new WeakOrderQueue(stack, thread) : null;
    }

WeakOrderQueue的構(gòu)造函數(shù)如下跟衅,WeakOrderQueue實現(xiàn)了多線程環(huán)境下回收對象的機制,當由其它線程回收對象到stack時會為該stack創(chuàng)建1個WeakOrderQueue播歼,這些由其它線程創(chuàng)建的WeakOrderQueue會在該stack中按鏈表形式串聯(lián)起來伶跷,每次創(chuàng)建1個WeakOrderQueue會把該WeakOrderQueue作為該stack的head WeakOrderQueue:

private WeakOrderQueue(Stack<?> stack, Thread thread) {
        head = tail = new Link();
        owner = new WeakReference<Thread>(thread);
        /**
         * 每次創(chuàng)建WeakOrderQueue時會更新WeakOrderQueue所屬的stack的head為當前WeakOrderQueue, 當前WeakOrderQueue的next為stack的之前head秘狞,
         * 這樣把該stack的WeakOrderQueue通過鏈表串起來了叭莫,當下次stack中沒有可用對象需要從WeakOrderQueue中轉(zhuǎn)移對象時從WeakOrderQueue鏈表的head進行scavenge轉(zhuǎn)移到stack的對DefaultHandle數(shù)組。
         */
        synchronized (stack) {
            next = stack.head;
            stack.head = this;
        }
        availableSharedCapacity = stack.availableSharedCapacity;
    }

下面再看Recycler.get()方法:

public final T get() {
    if (maxCapacity == 0) {
        return newObject(NOOP_HANDLE);
    }
    Stack<T> stack = threadLocal.get();
    DefaultHandle handle = stack.pop();
    if (handle == null) {
        handle = stack.newHandle();
        handle.value = newObject(handle);
    }
    return (T) handle.value;
}

取出該線程對應(yīng)的stack烁试,從stack中pop出1個DefaultHandle雇初,返回該DefaultHandle的真正對象。
下面看stack.pop()方法:

DefaultHandle pop() {
        int size = this.size;
        if (size == 0) {
            if (!scavenge()) {
                return null;
            }
            size = this.size;
        }
        size --;
        DefaultHandle ret = elements[size];
        elements[size] = null;
        if (ret.lastRecycledId != ret.recycleId) {
            throw new IllegalStateException("recycled multiple times");
        }
        ret.recycleId = 0;
        ret.lastRecycledId = 0;
        this.size = size;
        return ret;
    }

如果該stack的DefaultHandle數(shù)組中還有對象可用减响,那么從該DefaultHandle數(shù)組中取出1個可用對象返回靖诗,如果該DefaultHandle數(shù)組沒有可用的對象了,那么執(zhí)行scavenge()方法支示,將head WeakOrderQueue中的head Link中的DefaultHandle數(shù)組轉(zhuǎn)移到stack的DefaultHandle數(shù)組刊橘,scavenge方法如下:

boolean scavenge() {
        // continue an existing scavenge, if any
        if (scavengeSome()) {
            return true;
        }

        // reset our scavenge cursor
        prev = null;
        cursor = head;
        return false;
    }

具體執(zhí)行了scavengeSome()方法,清理WeakOrderQueue中部分DefaultHandle到stack颂鸿,每次盡可能清理head WeakOrderQueue的head Link的全部DefaultHandle促绵,如下:

boolean scavengeSome() {
        WeakOrderQueue cursor = this.cursor;
        if (cursor == null) {
            cursor = head;
            if (cursor == null) {
                return false;
            }
        }

        boolean success = false;
        WeakOrderQueue prev = this.prev;
        do {
            /**
             * 將當前WeakOrderQueue的head Link的DefaultHandle數(shù)組轉(zhuǎn)移到stack的DefaultHandle數(shù)組中
             */
            if (cursor.transfer(this)) {
                success = true;
                break;
            }

            WeakOrderQueue next = cursor.next;
            if (cursor.owner.get() == null) {
                if (cursor.hasFinalData()) {
                    for (;;) {
                        if (cursor.transfer(this)) {
                            success = true;
                        } else {
                            break;
                        }
                    }
                }
                if (prev != null) {
                    prev.next = next;
                }
            } else {
                prev = cursor;
            }

            cursor = next;

        } while (cursor != null && !success);

        this.prev = prev;
        this.cursor = cursor;
        return success;
    }

WeakOrderQueue.transfer()方法如下翘贮,將WeakOrderQueue的head Link中的DefaultHandle數(shù)組遷移到stack中:

boolean transfer(Stack<?> dst) {
        Link head = this.head;
        if (head == null) {
            return false;
        }

        /**
         * 如果head Link的readIndex到達了Link的容量LINK_CAPACITY昂秃,說明該Link已經(jīng)被scavengge完了。
         * 這時需要把下一個Link作為新的head Link粤攒。
         */
        if (head.readIndex == LINK_CAPACITY) {
            if (head.next == null) {
                return false;
            }
            this.head = head = head.next;
        }

        final int srcStart = head.readIndex;
        /**
         * head Link的回收對象數(shù)組的最大位置
         */
        int srcEnd = head.get();
        /**
         * head Link可以scavenge的DefaultHandle的數(shù)量
         */
        final int srcSize = srcEnd - srcStart;
        if (srcSize == 0) {
            return false;
        }

        final int dstSize = dst.size;

        /**
         * 每次會盡可能scavenge整個head Link栽渴,如果head Link的DefaultHandle數(shù)組能全部遷移到stack中尖坤,stack的DefaultHandle數(shù)組預(yù)期容量
         */
        final int expectedCapacity = dstSize + srcSize;
        /**
         * 如果預(yù)期容量大于stack的DefaultHandle數(shù)組最大長度,說明本次無法將head Link的DefaultHandle數(shù)組全部遷移到stack中
         */
        if (expectedCapacity > dst.elements.length) {
            final int actualCapacity = dst.increaseCapacity(expectedCapacity);
            srcEnd = min(srcStart + actualCapacity - dstSize, srcEnd);
        }

        if (srcStart != srcEnd) {
            /**
             * head Link的DefaultHandle數(shù)組
             */
            final DefaultHandle[] srcElems = head.elements;
            /**
             * stack的DefaultHandle數(shù)組
             */
            final DefaultHandle[] dstElems = dst.elements;
            int newDstSize = dstSize;
            /**
             * 遷移head Link的DefaultHandle數(shù)組到stack的DefaultHandle數(shù)組
             */
            for (int i = srcStart; i < srcEnd; i++) {
                DefaultHandle element = srcElems[i];
                if (element.recycleId == 0) {
                    element.recycleId = element.lastRecycledId;
                } else if (element.recycleId != element.lastRecycledId) {
                    throw new IllegalStateException("recycled already");
                }
                srcElems[i] = null;

                if (dst.dropHandle(element)) {
                    // Drop the object.
                    continue;
                }
                element.stack = dst;
                dstElems[newDstSize ++] = element;
            }

            /**
             * 當head節(jié)點的對象全都轉(zhuǎn)移給stack后闲擦,取head下一個節(jié)點作為head糖驴,下次轉(zhuǎn)移的時候再從新的head轉(zhuǎn)移回收的對象
             */
            if (srcEnd == LINK_CAPACITY && head.next != null) {
                // Add capacity back as the Link is GCed.
                reclaimSpace(LINK_CAPACITY);

                this.head = head.next;
            }
            /**
             * 遷移完成后更新原始head Link的readIndex
             */
            head.readIndex = srcEnd;
            if (dst.size == newDstSize) {
                return false;
            }
            dst.size = newDstSize;
            return true;
        } else {
            // The destination stack is full already.
            return false;
        }
    }
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末僚祷,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子贮缕,更是在濱河造成了極大的恐慌,老刑警劉巖俺榆,帶你破解...
    沈念sama閱讀 218,122評論 6 505
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件感昼,死亡現(xiàn)場離奇詭異,居然都是意外死亡罐脊,警方通過查閱死者的電腦和手機定嗓,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,070評論 3 395
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來萍桌,“玉大人宵溅,你說我怎么就攤上這事∩涎祝” “怎么了恃逻?”我有些...
    開封第一講書人閱讀 164,491評論 0 354
  • 文/不壞的土叔 我叫張陵,是天一觀的道長藕施。 經(jīng)常有香客問我寇损,道長,這世上最難降的妖魔是什么裳食? 我笑而不...
    開封第一講書人閱讀 58,636評論 1 293
  • 正文 為了忘掉前任矛市,我火速辦了婚禮,結(jié)果婚禮上诲祸,老公的妹妹穿的比我還像新娘浊吏。我一直安慰自己,他們只是感情好救氯,可當我...
    茶點故事閱讀 67,676評論 6 392
  • 文/花漫 我一把揭開白布找田。 她就那樣靜靜地躺著,像睡著了一般径密。 火紅的嫁衣襯著肌膚如雪午阵。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,541評論 1 305
  • 那天享扔,我揣著相機與錄音底桂,去河邊找鬼。 笑死惧眠,一個胖子當著我的面吹牛籽懦,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播氛魁,決...
    沈念sama閱讀 40,292評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼暮顺,長吁一口氣:“原來是場噩夢啊……” “哼厅篓!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起捶码,我...
    開封第一講書人閱讀 39,211評論 0 276
  • 序言:老撾萬榮一對情侶失蹤羽氮,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后惫恼,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體档押,經(jīng)...
    沈念sama閱讀 45,655評論 1 314
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,846評論 3 336
  • 正文 我和宋清朗相戀三年祈纯,在試婚紗的時候發(fā)現(xiàn)自己被綠了令宿。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 39,965評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡腕窥,死狀恐怖粒没,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情簇爆,我是刑警寧澤癞松,帶...
    沈念sama閱讀 35,684評論 5 347
  • 正文 年R本政府宣布,位于F島的核電站冕碟,受9級特大地震影響拦惋,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜安寺,卻給世界環(huán)境...
    茶點故事閱讀 41,295評論 3 329
  • 文/蒙蒙 一厕妖、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧挑庶,春花似錦言秸、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,894評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至凳枝,卻和暖如春抄沮,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背岖瑰。 一陣腳步聲響...
    開封第一講書人閱讀 33,012評論 1 269
  • 我被黑心中介騙來泰國打工叛买, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人蹋订。 一個月前我還...
    沈念sama閱讀 48,126評論 3 370
  • 正文 我出身青樓率挣,卻偏偏與公主長得像,于是被迫代替她去往敵國和親露戒。 傳聞我的和親對象是個殘疾皇子椒功,可洞房花燭夜當晚...
    茶點故事閱讀 44,914評論 2 355

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

  • 從三月份找實習(xí)到現(xiàn)在捶箱,面了一些公司,掛了不少动漾,但最終還是拿到小米丁屎、百度、阿里谦炬、京東悦屏、新浪、CVTE键思、樂視家的研發(fā)崗...
    時芥藍閱讀 42,246評論 11 349
  • 1. Java基礎(chǔ)部分 基礎(chǔ)部分的順序:基本語法,類相關(guān)的語法甫贯,內(nèi)部類的語法吼鳞,繼承相關(guān)的語法,異常的語法叫搁,線程的語...
    子非魚_t_閱讀 31,631評論 18 399
  • Java SE 基礎(chǔ): 封裝赔桌、繼承、多態(tài) 封裝: 概念:就是把對象的屬性和操作(或服務(wù))結(jié)合為一個獨立的整體渴逻,并盡...
    Jayden_Cao閱讀 2,109評論 0 8
  • 什么是對象池技術(shù)疾党?對象池應(yīng)用在哪些地方? 對象池其實就是緩存一些對象從而避免大量創(chuàng)建同一個類型的對象惨奕,類似線程池的...
    BlackManba_24閱讀 4,322評論 0 8
  • (續(xù)二十二) 袁崇煥誅殺毛文龍雪位,是他一生中所犯的最嚴重錯誤之一。毛文龍祖籍山西生于浙江梨撞,是明末遼東邊防的一員重要將...
    幽明劉旭音閱讀 217評論 0 2