淺析LRUCache原理(Android)

一. LruCache基本原理

LRU全稱爲Least Recently Used,即最近最少使用。

由於緩存容量是有限的,當有新的數據需要加入緩存,但緩存的空閒空間不足的時候,如何移除原有的部分數據從而釋放空間用來放新的數據?

LRU算法就是當緩存空間滿了的時候,將最近最少使用的數據從緩存空間中刪除以增加可用的緩存空間來緩存新數據。

這個算分的內部有一個緩存列表,每當一個緩存數據被訪問的時候,這個數據就會被提到列表尾部,每次都這樣的話,列表的頭部數據就是最近最不常使用的了,當緩存空間不足時,就會刪除列表頭部的緩存數據。

二. LruCache的使用

//獲取系統分配給每個應用程序的最大內存
int maxMemory=(int)(Runtime.getRuntime().maxMemory()/1024);
int cacheSize=maxMemory/8; 
private LruCache<String, Bitmap> mMemoryCache;
//給LruCache分配1/8 
mMemoryCache = new LruCache<String, Bitmap>(mCacheSize){  
    //重寫該方法,來測量Bitmap的大小  
    @Override  
    protected int sizeOf(String key, Bitmap value) {  
        return value.getRowBytes() * value.getHeight()/1024;  
    }  
};

三. LruCache部分源碼解析

LruCache 利用 LinkedHashMap 的一個特性(accessOrder=true 基於訪問順序)再加上對 LinkedHashMap 的數據操作上鎖實現的緩存策略。

LruCache 的數據緩存是內存中的。

  • 首先設置了內部 LinkedHashMap 構造參數 accessOrder=true, 實現了數據排序按照訪問順序。
  • LruCache類在調用get(K key) 方法時,都會調用LinkedHashMap.get(Object key) 。
  • 如上述設置了 accessOrder=true 後,調用LinkedHashMap.get(Object key) 都會通過LinkedHashMap的afterNodeAccess()方法將數據移到隊尾。
  • 由於最新訪問的數據在尾部,在 put 和 trimToSize 的方法執行下,如果發生數據移除,會優先移除掉頭部數據

1.構造方法


    /**
     * @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);
    }

LinkedHashMap參數介紹:

  • initialCapacity 用於初始化該 LinkedHashMap 的大小。

  • loadFactor(負載因子)這個LinkedHashMap的父類 HashMap 裏的構造參數,涉及到擴容問題,比如 HashMap 的最大容量是100,那麼這裏設置0.75f的話,到75的時候就會擴容。

  • accessOrder,這個參數是排序模式,true表示在訪問的時候進行排序( LruCache 核心工作原理就在此),false表示在插入的時才排序。

2.添加數據 LruCache.put(K key, V value)

/**
     * 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++;
             //safeSizeOf(key, value)。
             //這個方法返回的是1,也就是將緩存的個數加1.
            // 當緩存的是圖片的時候,這個size應該表示圖片佔用的內存的大小,所以應該重寫裏面調用的sizeOf(key, value)方法
            size += safeSizeOf(key, value);
            //向map中加入緩存對象,若緩存中已存在,返回已有的值,否則執行插入新的數據,並返回null
            previous = map.put(key, value);
            //如果已有緩存對象,則緩存大小恢復到之前
            if (previous != null) {
                size -= safeSizeOf(key, previous);
            }
        }
          //entryRemoved()是個空方法,可以自行實現
        if (previous != null) {
            entryRemoved(false, key, previous, value);
        }

        trimToSize(maxSize);
        return previous;
    }
  • 開始的時候確實是把值放入LinkedHashMap,不管超不超過你設定的緩存容量。
  • 根據 safeSizeOf方法計算 此次添加數據的容量是多少,並且加到size 裏 。
  • 方法執行到最後時,通過trimToSize()方法 來判斷size 是否大於maxSize。

可以看到put()方法並沒有太多的邏輯,重要的就是在添加過緩存對象後,調用 trimToSize()方法,來判斷緩存是否已滿,如果滿了就要刪除近期最少使用的數據。

2.trimToSize(int maxSize)

/**
     * 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) {
              //如果map爲空並且緩存size不等於0或者緩存size小於0,拋出異常
                if (size < 0 || (map.isEmpty() && size != 0)) {
                    throw new IllegalStateException(getClass().getName()
                            + ".sizeOf() is reporting inconsistent results!");
                }
     //如果緩存大小size小於最大緩存,不需要再刪除緩存對象,跳出循環
                if (size <= maxSize) {
                    break;
                }
     //在緩存隊列中查找最近最少使用的元素,若不存在,直接退出循環,若存在則直接在map中刪除。
                Map.Entry<K, V> toEvict = map.eldest();
                if (toEvict == null) {
                    break;
                }

                key = toEvict.getKey();
                value = toEvict.getValue();
                map.remove(key);
                size -= safeSizeOf(key, value);
                //回收次數+1
                evictionCount++;
            }

            entryRemoved(true, key, value, null);
        }
    }
/**
 * Returns the eldest entry in the map, or {@code null} if the map is empty.
 *
 * Android-added.
 *
 * @hide
 */
public Map.Entry<K, V> eldest() {
    Entry<K, V> eldest = header.after;
    return eldest != header ? eldest : null;
}

trimToSize()方法不斷地刪除LinkedHashMap中隊首的元素,即近期最少訪問的,直到緩存大小小於最大值。

3.LruCache.get(K key)

    /**
     * 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.
     * 通過key獲取緩存的數據,如果通過這個方法得到的需要的元素,那麼這個元素會被放在緩存隊列的尾部,
     * 
     */
    public final V get(K key) {
        if (key == null) {
            throw new NullPointerException("key == null");
        }

        V mapValue;
        synchronized (this) {
              //從LinkedHashMap中獲取數據。
            mapValue = map.get(key);
            if (mapValue != null) {
                hitCount++;
                return mapValue;
            }
            missCount++;
        }
    /*
     * 正常情況走不到下面
     * 因爲默認的 create(K key) 邏輯爲null
     * 走到這裏的話說明實現了自定義的create(K key) 邏輯,比如返回了一個不爲空的默認值
     */
        /*
         * 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.
         * 譯:如果通過key從緩存集合中獲取不到緩存數據,就嘗試使用creat(key)方法創造一個新數據。
         * create(key)默認返回的也是null,需要的時候可以重寫這個方法。
         */

        V createdValue = create(key);
        if (createdValue == null) {
            return null;
        }
        //如果重寫了create(key)方法,創建了新的數據,就講新數據放入緩存中。
        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;
        }
    }

當調用LruCache的get()方法獲取集合中的緩存對象時,就代表訪問了一次該元素,將會更新隊列,保持整個隊列是按照訪問順序排序,這個更新過程就是在LinkedHashMap中的get()方法中完成的。

總結

  • LruCache中維護了一個集合LinkedHashMap,該LinkedHashMap是以訪問順序排序的。
  • 當調用put()方法時,就會在結合中添加元素,並調用trimToSize()判斷緩存是否已滿,如果滿了就用LinkedHashMap的迭代器刪除隊首元素,即近期最少訪問的元素。
  • 當調用get()方法訪問緩存對象時,就會調用LinkedHashMap的get()方法獲得對應集合元素,同時會更新該元素到隊尾。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章