LRU全稱爲Least Recently Used,即最近最少使用。算法
因爲緩存容量是有限的,當有新的數據須要加入緩存,但緩存的空閒空間不足的時候,如何移除原有的部分數據從而釋放空間用來放新的數據?緩存
LRU算法就是當緩存空間滿了的時候,將最近最少使用的數據從緩存空間中刪除以增長可用的緩存空間來緩存新數據。app
這個算分的內部有一個緩存列表,每當一個緩存數據被訪問的時候,這個數據就會被提到列表尾部,每次都這樣的話,列表的頭部數據就是最近最不常使用的了,當緩存空間不足時,就會刪除列表頭部的緩存數據。ide
//獲取系統分配給每一個應用程序的最大內存 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 利用 LinkedHashMap 的一個特性(accessOrder=true 基於訪問順序)再加上對 LinkedHashMap 的數據操做上鎖實現的緩存策略。this
LruCache 的數據緩存是內存中的。spa
/** * @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參數介紹:code
initialCapacity 用於初始化該 LinkedHashMap 的大小。對象
loadFactor(負載因子)這個LinkedHashMap的父類 HashMap 裏的構造參數,涉及到擴容問題,好比 HashMap 的最大容量是100,那麼這裏設置0.75f的話,到75的時候就會擴容。排序
accessOrder,這個參數是排序模式,true表示在訪問的時候進行排序( LruCache 核心工做原理就在此),false表示在插入的時才排序。隊列
/** * 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; }
能夠看到put()方法並無太多的邏輯,重要的就是在添加過緩存對象後,調用 trimToSize()方法,來判斷緩存是否已滿,若是滿了就要刪除近期最少使用的數據。
/** * 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中隊首的元素,即近期最少訪問的,直到緩存大小小於最大值。
/** * 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()方法中完成的。