Java&Android 基礎知識梳理(9) - LruCache 源碼解析

一、基本概念

1.1 LruCache 的作用

LruCache的基本思想是Least Recently Used,即 最近最少使用,也就是當LruCache內部緩存在內存中的對象大小之和到達設定的閾值后,會刪除 訪問時間距離當前最久 的對象,從而避免了OOM的發生。

LruCache特別適用于圖片內存緩存這種有可能需要占用很多內存,但是只有最近使用的對象才有可能用到的場景。

1.2 LruCache 的使用

下面,我們用一個例子來演示一下LruCache的使用,讓大家有一個初步的認識。

public class LruCacheSamples {

    private static final int MAX_SIZE = 50;

    public static void startRun() {
        LruCacheSample sample = new LruCacheSample();
        Log.d("LruCacheSample", "Start Put Object1, size=" + sample.size());
        sample.put("Object1", new Holder("Object1", 10));

        Log.d("LruCacheSample", "Start Put Object2, size=" + sample.size());
        sample.put("Object2", new Holder("Object2", 20));

        Log.d("LruCacheSample", "Start Put Object3, size=" + sample.size());
        sample.put("Object3", new Holder("Object3", 30));

        Log.d("LruCacheSample", "Start Put Object4, size=" + sample.size());
        sample.put("Object4", new Holder("Object4", 10));
    }

    static class LruCacheSample extends LruCache<String, Holder> {

        LruCacheSample() {
            super(MAX_SIZE);
        }

        @Override
        protected int sizeOf(String key, Holder value) {
            return value.getSize();
        }

        @Override
        protected void entryRemoved(boolean evicted, String key, Holder oldValue, Holder newValue) {
            if (oldValue != null) {
                Log.d("LruCacheSample", "remove=" + oldValue.getName());
            }
            if (newValue != null) {
                Log.d("LruCacheSample", "add=" + newValue.getName());
            }
        }
    }

    static class Holder {

        private String mName;
        private int mSize;

        Holder(String name, int size) {
            mName = name;
            mSize = size;
        }

        public String getName() {
            return mName;
        }

        public int getSize() {
            return mSize;
        }
    }
}

運行結果為:

運行結果

在放入Object3之后,由于放入之前LruCache的大小為30,而Object3的大小為30,放入之后的大小為60,超過了最先設定的最大值50,因此會移除最先插入的Object1,減去該元素的大小10,最新的大小變為50

二、源碼解析

2.1 構造函數

首先看一下LruCache的構造函數:

    /**
     * @param maxSize for caches that do not override {@link #sizeOf}, this is
     *     the maximum number of entries in the cache. For all other caches,
     *     this is the maximum sum of the sizes of the entries in this cache.
     */
    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);
    }

當我們創建一個LruCache類時需要指定一個最大的閾值maxSize,而我們的對象會緩存在LinkedHashMap當中:

  • maxSize等于LinkedHashMap中每個元素的sizeOf(key, value)之和,默認情況下每個對象的大小為1,使用者可以通過重寫sizeOf指定對應元素的大小。
  • LinkedHashMap是實現LRU算法的核心,它會根據對象的使用情況維護一個雙向鏈表,其內部的header.after指向歷史最悠久的元素,而header.before指向最年輕的元素,這一“年齡”的依據可以是訪問的順序,也可以是寫入的順序。

2.2 put 流程

接下來看一下與put相關的方法:

    /**
     * Caches {@code value} for {@code key}. The value is moved to the head of
     * the queue.
     *
     * @return the previous value mapped by {@code key}.
     */
    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++;
            //獲得該對象的大小,由 LruCache 的使用者來決定,要求返回值大于等于 0,否則拋出異常。
            size += safeSizeOf(key, value);
            //調用的是 HashMap 的 put 方法,previous 是之前該 key 值存放的對象。
            previous = map.put(key, value);
            //如果已經存在,由于它現在被替換成了新的 value,所以需要減去這個大小。
            if (previous != null) {
                size -= safeSizeOf(key, previous);
            }
        }
        //通知使用者該對象被移除了。
        if (previous != null) {
            entryRemoved(false, key, previous, value);
        }
        //由于放入了新的對象,因此需要確保目前總的容量沒有超過設定的閾值。
        trimToSize(maxSize);
        return previous;
    }

    private int safeSizeOf(K key, V value) {
        int result = sizeOf(key, value);
        if (result < 0) {
            throw new IllegalStateException("Negative size: " + key + "=" + value);
        }
        return result;
    }

    /**
     * Returns the size of the entry for {@code key} and {@code value} in
     * user-defined units.  The default implementation returns 1 so that size
     * is the number of entries and max size is the maximum number of entries.
     *
     * <p>An entry's size must not change while it is in the cache.
     */
    protected int sizeOf(K key, V value) {
        //默認情況下,每個對象的權重值為 1。
        return 1;
    }

    /**
     * Remove the eldest entries until the total of remaining entries is at or
     * below the requested size.
     *
     * @param maxSize the maximum size of the cache before returning. May be -1
     *            to evict even 0-sized elements.
     */
    public void trimToSize(int maxSize) {
        while (true) {
            K key;
            V value;
            synchronized (this) {
                if (size < 0 || (map.isEmpty() && size != 0)) {
                    throw new IllegalStateException(getClass().getName()
                            + ".sizeOf() is reporting inconsistent results!");
                }
                //這是一個 while 循環,因此將一直刪除最悠久的結點,直到小于閾值。
                if (size <= maxSize) {
                    break;
                }
                //獲得歷史最悠久的結點。
                Map.Entry<K, V> toEvict = map.eldest();
                if (toEvict == null) {
                    break;
                }

                key = toEvict.getKey();
                value = toEvict.getValue();
                //從 map 中將它移除。
                map.remove(key);
                size -= safeSizeOf(key, value);
                evictionCount++;
            }
            //通知使用者該對象被移除了。
            entryRemoved(true, key, value, null);
        }
    }

關于代碼的解釋都在注釋中了,其核心的思想就是在每放入一個元素之后,通過sizeOf來獲得這個元素的權重值,如果發現所有元素的權重值之和大于size,那么就通過trimToSize移除歷史最悠久的元素,并通過entryRemoved回調給LruCache的實現者。

2.3 get 流程

    /**
     * Returns the value for {@code key} if it exists in the cache or can be
     * created by {@code #create}. If a value was returned, it is moved to the
     * head of the queue. This returns null if a value is not cached and cannot
     * be created.
     */
    public final V get(K key) {
        //與 HashMap 不同,LruCache 不允許 key 值為空。
        if (key == null) {
            throw new NullPointerException("key == null");
        }

        V mapValue;
        synchronized (this) {
            //首先在 map 中查找,如果找到了就直接返回。
            mapValue = map.get(key);
            if (mapValue != null) {
                hitCount++;
                return mapValue;
            }
            missCount++;
        }

        //如果在 map 中沒有找到,get 方法不會直接返回 null,而是先回調 create 方法,讓使用者有一個創建的機會。
        V createdValue = create(key);
        //如果使用者沒有重寫 create 方法,那么會返回 null。
        if (createdValue == null) {
            return null;
        }

        synchronized (this) {
            createCount++;
            //由于 create 的過程沒有加入同步塊,因此有可能在創建的過程中,使用者通過 put 方法在 map 相同的位置放入了一個對象,這個對象是 mapValue。
            mapValue = map.put(key, createdValue);
            //如果存在上面的情況,那么會拋棄掉 create 方法創建對象,重新放入已經存在于 map 中的對象。
            if (mapValue != null) {
                map.put(key, mapValue);
            } else {
                //增加總的權重大小。
                size += safeSizeOf(key, createdValue);
            }
        }
        //如果存在沖突的情況,那么要通知使用者這一變化,但是有大小并沒有改變,所以不需要重新計算大小。
        if (mapValue != null) {
            entryRemoved(false, key, createdValue, mapValue);
            return mapValue;
        } else {
            //由于大小改變了,因此需要重新計算大小。
            trimToSize(maxSize);
            return createdValue;
        }
    }

這里需要特別說明一下LruCacheHashMapget方法的區別:如果LinkedHashMap中不存在Key對應的Valueget方法并像HashMap一樣直接返回,而是先 通過create方法嘗試讓使用者重新創建一個對象,如果創建成功,那么將會把這個對象放入到集合當中,并返回這個新創建的對象。

上面這種是單線程的情況,如果在多線程的情況下,由于create方法沒有加入synchronized關鍵字,因此有可能 一個線程在create方法創建對象的過程中,另一個線程又通過put方法在Key對應的相同位置放入一個對象,在這種情況下,將會拋棄掉由create創建的對象,維持原有的狀態。

2.4 LinkedHashMap

通過get/set方法,我們可以知道LruCache是通過trimToSize來保證它所維護的對象的權重之和不超過maxSize,最后我們再來分析一下LinkedHashMap,看下它是如何保證每次大小超過maxSize時,移除的都是歷史最悠久的元素的。

LinkedHashMap繼承于HashMap,它通過重寫相關的方法在HashMap的基礎上實現了雙向鏈表的特性。

2.4.1 Entry 元素

LinkedHashMap重新定義了HashMap數組中的HashMapEntry,它的實現為LinkedHashMapEntry,除了原有的nextkeyvaluehash值以外,它還額外地保存了afterbefore兩個指針,用來實現根據寫入順序或者讀取順序來排列的雙向鏈表。

    private static class LinkedHashMapEntry<K,V> extends HashMapEntry<K,V> {

        LinkedHashMapEntry<K,V> before, after;

        LinkedHashMapEntry(int hash, K key, V value, HashMapEntry<K,V> next) {
            super(hash, key, value, next);
        }
        
        //刪除鏈表結點。
        private void remove() {
            before.after = after;
            after.before = before;
        }
        
        //在 existingEntry 之前插入該結點。
        private void addBefore(LinkedHashMapEntry<K,V> existingEntry) {
            after  = existingEntry;
            before = existingEntry.before;
            before.after = this;
            after.before = this;
        }
        
        //如果是按訪問順序排列,那么將該結點插入到整個鏈表的頭部。
        void recordAccess(HashMap<K,V> m) {
            LinkedHashMap<K,V> lm = (LinkedHashMap<K,V>)m;
            if (lm.accessOrder) {
                lm.modCount++;
                remove();
                addBefore(lm.header);
            }
        }

        //從鏈表中移除該結點。
        void recordRemoval(HashMap<K,V> m) {
            remove();
        }
    }

2.4.2 初始化

LinkedHashMap重寫了init()方法,該方法會在其父類HashMap的構造函數中被調用,在init()方法中,會初始化一個空的LinkedHashMapEntry結點header,它的before指向最年輕的元素,而after指向歷史最悠久的元素。

    void init() {
        header = new LinkedHashMapEntry<>(-1, null, null, null);
        header.before = header.after = header;
    }

LinkedHashMap的構造函數中,可以傳入accessOrder,如果accessOrdertrue,那么“歷史最悠久”的元素表示的是訪問時間距離當前最久的元素,即按照訪問順序排列;如果為false,那么表示最先插入的元素,即按照插入順序排列,默認的值為false

2.4.3 元素寫入

對于元素的寫入,LinkedHashMap并沒有重寫put方法,而是重寫了addEntry/createEntry方法,在創建結點的同時,更新它所維護的雙向鏈表。

    void addEntry(int hash, K key, V value, int bucketIndex) {
        LinkedHashMapEntry<K,V> eldest = header.after;
        if (eldest != header) {
            boolean removeEldest;
            size++;
            try {
                removeEldest = removeEldestEntry(eldest);
            } finally {
                size--;
            }
            if (removeEldest) {
                removeEntryForKey(eldest.key);
            }
        }
        super.addEntry(hash, key, value, bucketIndex);
    }

    void createEntry(int hash, K key, V value, int bucketIndex) {
        HashMapEntry<K,V> old = table[bucketIndex];
        LinkedHashMapEntry<K,V> e = new LinkedHashMapEntry<>(hash, key, value, old);
        table[bucketIndex] = e;
        e.addBefore(header);
        size++;
    }

2.4.4 元素讀取

對于元素的讀取,LinkedHashMap重寫了get方法,它首先調用HashMapgetEntry方法找到結點,如果判斷是需要根據訪問的順序來排列雙向列表,那么就需要對鏈表進行更新,即調用我們在2.4.1中看到的recordAccess方法。

    public V get(Object key) {
        LinkedHashMapEntry<K,V> e = (LinkedHashMapEntry<K,V>)getEntry(key);
        if (e == null)
            return null;
        e.recordAccess(this);
        return e.value;
    }

三、參考文獻

深入 Java 集合學習系列:LinkedHashMap 的實現原理

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。