LruCache源碼淺析

前言:自從Andorid3.1之后,谷歌引入了LruCache沪曙,官方文檔說(shuō)明如下:

 * A cache that holds strong references to a limited number of values. Each time
 * a value is accessed, it is moved to the head of a queue. When a value is
 * added to a full cache, the value at the end of that queue is evicted and may
 * become eligible for garbage collection.
 *
 * <p>If your cached values hold resources that need to be explicitly released,
 * override {@link #entryRemoved}.
 *
 * <p>If a cache miss should be computed on demand for the corresponding keys,
 * override {@link #create}. This simplifies the calling code, allowing it to
 * assume a value will always be returned, even when there's a cache miss.
 *
 * <p>By default, the cache size is measured in the number of entries. Override
 * {@link #sizeOf} to size the cache in different units. For example, this cache
 *
 * <p>This class does not allow null to be used as a key or value. A return
 * value of null from {@link #get}, {@link #put} or {@link #remove} is
 * unambiguous: the key was not in the cache.
 *
  • 官方文檔指出幾點(diǎn):
    --hold strong reference: 該緩存引用的是強(qiáng)引用。
    --a value is accessed, it is moved to the head of a queue :每次一個(gè)數(shù)據(jù)被訪問(wèn)萎羔,就會(huì)被移到對(duì)頭
    --要重載sizeof用于測(cè)量當(dāng)前內(nèi)存大小
    --不支持空的key液走。

LRU:什么是LRU算法? LRU是Least Recently Used的縮寫贾陷,即最近最少使用
LruCache里面最重要的是維護(hù)了一個(gè)雙向鏈表(該鏈表支持有序插入)用于存放緩存數(shù)據(jù),LinkedHashMap底層正是實(shí)現(xiàn)了LRU算法.

    private final LinkedHashMap<K, V> map;

LinkedHashMap :

  • LinkedHashMap is an implementation of {@link Map} that guarantees > iteration order.
  • All optional operations are supported.
  • <p>All elements are permitted as keys or values, including null.
  • <p>Entries are kept in a doubly-linked list. The iteration order is, by > > > default, theorder in which keys were inserted. Reinserting an already-present key > doesn't change theorder. If the three argument constructor is used, and {@code accessOrder} is specified as
    {@code true}, the iteration will be in the order that entries were accessed.
  • The access order is affected by {@code put}, {@code get}, and {@code putAll} operations,
  • but not by operations on the collection views.

LinkedHashMap 繼承HashMap,里面維護(hù)一個(gè)內(nèi)部類LinkeEntry雙向鏈表用于存儲(chǔ)數(shù)據(jù)育灸。
具體分析可以看該博客:圖解LinkedHashMap原理


我們先開LruCache的構(gòu)造函數(shù)

    public LruCache(int maxSize) {
        if (maxSize <= 0) {
            throw new IllegalArgumentException("maxSize <= 0");
        }
        this.maxSize = maxSize;
        this.map = new LinkedHashMap<K, V>(0, 0.75f, true);
    }

構(gòu)造了一個(gè)LinkedHashMap,而且第三個(gè)參數(shù)為true昵宇,表示訪問(wèn)有序(這個(gè)是實(shí)現(xiàn)該LruCache算法的核心磅崭。)

put函數(shù):

public final V put(K key, V value) {
        if (key == null || value == null) {
            throw new NullPointerException("key == null || value == null");
        }

        V previous;
        synchronized (this) {
            putCount++;
            size += safeSizeOf(key, value);
            previous = map.put(key, value);
            if (previous != null) {
                size -= safeSizeOf(key, previous);
            }
        }

        if (previous != null) {
            entryRemoved(false, key, previous, value);
        }

        trimToSize(maxSize);
        return previous;
    }

分析:
每次放入一個(gè)數(shù)據(jù),size會(huì)根據(jù)當(dāng)前的數(shù)據(jù)大小增加

    private int safeSizeOf(K key, V value) {
        int result = sizeOf(key, value);//該方法就是上面說(shuō)的要重寫的方法
        if (result < 0) {
            throw new IllegalStateException("Negative size: " + key + "=" + value);
        }
        return result;
    }

然后將數(shù)據(jù)放入map瓦哎,返回一個(gè)previous,其中砸喻,map.put(key, value):
HashMap.java

    @Override public V put(K key, V value) {
        if (key == null) {
            return putValueForNullKey(value);
        }

        int hash = Collections.secondaryHash(key);
        HashMapEntry<K, V>[] tab = table;
        int index = hash & (tab.length - 1);
        for (HashMapEntry<K, V> e = tab[index]; e != null; e = e.next) {
            if (e.hash == hash && key.equals(e.key)) {
                preModify(e);
                V oldValue = e.value;
                e.value = value;
                return oldValue;
            }
        }

        // No entry for (non-null) key is present; create one
        modCount++;
        if (size++ > threshold) {
            tab = doubleCapacity();
            index = hash & (tab.length - 1);
        }
        addNewEntry(key, value, hash, index);
        return null;
    }

當(dāng)當(dāng)前的key在map里面是有的時(shí)候柔逼,返回舊的數(shù)據(jù),并且被回收掉。

if (previous != null) {
                size -= safeSizeOf(key, previous);
            }
        }

        if (previous != null) {
            entryRemoved(false, key, previous, value);
        }

public void trimToSize(int maxSize) {
        while (true) {
            K key;
            V value;
            synchronized (this) {
                //如果重載的sizeof方法返回的大小單位跟max傳入的大小單位不同割岛,這里會(huì)報(bào)錯(cuò)
                if (size < 0 || (map.isEmpty() && size != 0)) {
                    throw new IllegalStateException(getClass().getName()
                            + ".sizeOf() is reporting inconsistent results!");
                }

                if (size <= maxSize) {
                    break;
                }

                Map.Entry<K, V> toEvict = map.eldest();
                if (toEvict == null) {
                    break;
                }

                key = toEvict.getKey();
                value = toEvict.getValue();
                map.remove(key);
                size -= safeSizeOf(key, value);
                evictionCount++;
            }

            entryRemoved(true, key, value, null);
        }

對(duì)緩存進(jìn)行內(nèi)存裁剪愉适,不斷第將隊(duì)尾的數(shù)據(jù)刪除,直到size<=maxSize.

其中最關(guān)鍵的就是map.eldest()這段代碼癣漆,拿到當(dāng)前最老的數(shù)據(jù)维咸,也就是說(shuō)最近最少訪問(wèn)的數(shù)據(jù)。

    public Entry<K, V> eldest() {
        LinkedEntry<K, V> eldest = header.nxt;
        return eldest != header ? eldest : null;
    }

由于在構(gòu)造LinkedMap的時(shí)候惠爽,構(gòu)造參數(shù)accessOrder是true,也就是說(shuō)當(dāng)前的鏈表的順序是根據(jù)訪問(wèn)時(shí)間去定當(dāng)前數(shù)據(jù)的位置癌蓖,越久沒訪問(wèn),越前婚肆。

LinkedHashMap:
    /**
     * Relinks the given entry to the tail of the list. Under access ordering,
     * this method is invoked whenever the value of a  pre-existing entry is
     * read by Map.get or modified by Map.put.
     */
    private void makeTail(LinkedEntry<K, V> e) {
        // Unlink e
        e.prv.nxt = e.nxt;
        e.nxt.prv = e.prv;

        // Relink e as tail
        LinkedEntry<K, V> header = this.header;
        LinkedEntry<K, V> oldTail = header.prv;
        e.nxt = header;
        e.prv = oldTail;
        oldTail.nxt = header.prv = e;
        modCount++;
    }

上面就是每次調(diào)整數(shù)據(jù)順序的代碼租副。

--在如果做圖片處理的時(shí)候,可以復(fù)寫entryRemoved對(duì)從map里面移除的圖片進(jìn)行復(fù)用內(nèi)存较性。

get方法:

public final V get(K key) {
        if (key == null) {
            throw new NullPointerException("key == null");
        }

        V mapValue;
        synchronized (this) {
            mapValue = map.get(key);
            if (mapValue != null) {
                hitCount++;
                return mapValue;
            }
            missCount++;
        }

        /*
         * Attempt to create a value. This may take a long time, and the map
         * may be different when create() returns. If a conflicting value was
         * added to the map while create() was working, we leave that value in
         * the map and release the created value.
         */

        V createdValue = create(key);
        if (createdValue == null) {
            return null;
        }

      //下面代碼跟put的代碼差不多用僧,也是新建一個(gè)value放入map
        synchronized (this) {
            createCount++;
            mapValue = map.put(key, createdValue);

            if (mapValue != null) {
                // There was a conflict so undo that last put
                map.put(key, mapValue);
            } else {
                size += safeSizeOf(key, createdValue);
            }
        }

        if (mapValue != null) {
            entryRemoved(false, key, createdValue, mapValue);
            return mapValue;
        } else {
            trimToSize(maxSize);
            return createdValue;
        }
    }

該方法有個(gè)特殊的地方就是,如果map里面沒有對(duì)應(yīng)的key的數(shù)據(jù)或者出于其他原因key對(duì)應(yīng)的數(shù)據(jù)被刪除了赞咙,提供了create(key)方法給用于去重新創(chuàng)建對(duì)應(yīng)的數(shù)據(jù)责循。

LruCache

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市攀操,隨后出現(xiàn)的幾起案子沼死,更是在濱河造成了極大的恐慌,老刑警劉巖崔赌,帶你破解...
    沈念sama閱讀 216,651評(píng)論 6 501
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件意蛀,死亡現(xiàn)場(chǎng)離奇詭異,居然都是意外死亡健芭,警方通過(guò)查閱死者的電腦和手機(jī)县钥,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,468評(píng)論 3 392
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái)慈迈,“玉大人若贮,你說(shuō)我怎么就攤上這事⊙髁簦” “怎么了谴麦?”我有些...
    開封第一講書人閱讀 162,931評(píng)論 0 353
  • 文/不壞的土叔 我叫張陵,是天一觀的道長(zhǎng)伸头。 經(jīng)常有香客問(wèn)我匾效,道長(zhǎng),這世上最難降的妖魔是什么恤磷? 我笑而不...
    開封第一講書人閱讀 58,218評(píng)論 1 292
  • 正文 為了忘掉前任面哼,我火速辦了婚禮野宜,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘魔策。我一直安慰自己匈子,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,234評(píng)論 6 388
  • 文/花漫 我一把揭開白布闯袒。 她就那樣靜靜地躺著虎敦,像睡著了一般。 火紅的嫁衣襯著肌膚如雪政敢。 梳的紋絲不亂的頭發(fā)上其徙,一...
    開封第一講書人閱讀 51,198評(píng)論 1 299
  • 那天,我揣著相機(jī)與錄音堕仔,去河邊找鬼。 笑死晌区,一個(gè)胖子當(dāng)著我的面吹牛摩骨,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播朗若,決...
    沈念sama閱讀 40,084評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼恼五,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼!你這毒婦竟也來(lái)了哭懈?” 一聲冷哼從身側(cè)響起灾馒,我...
    開封第一講書人閱讀 38,926評(píng)論 0 274
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤,失蹤者是張志新(化名)和其女友劉穎遣总,沒想到半個(gè)月后睬罗,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,341評(píng)論 1 311
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡旭斥,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,563評(píng)論 2 333
  • 正文 我和宋清朗相戀三年容达,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片垂券。...
    茶點(diǎn)故事閱讀 39,731評(píng)論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡花盐,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出菇爪,到底是詐尸還是另有隱情算芯,我是刑警寧澤,帶...
    沈念sama閱讀 35,430評(píng)論 5 343
  • 正文 年R本政府宣布凳宙,位于F島的核電站熙揍,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏氏涩。R本人自食惡果不足惜诈嘿,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,036評(píng)論 3 326
  • 文/蒙蒙 一堪旧、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧奖亚,春花似錦淳梦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,676評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)。三九已至作郭,卻和暖如春陨囊,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背夹攒。 一陣腳步聲響...
    開封第一講書人閱讀 32,829評(píng)論 1 269
  • 我被黑心中介騙來(lái)泰國(guó)打工蜘醋, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人咏尝。 一個(gè)月前我還...
    沈念sama閱讀 47,743評(píng)論 2 368
  • 正文 我出身青樓压语,卻偏偏與公主長(zhǎng)得像,于是被迫代替她去往敵國(guó)和親编检。 傳聞我的和親對(duì)象是個(gè)殘疾皇子胎食,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,629評(píng)論 2 354