Android快取機制——LruCache
概述
LruCache的核心原理就是對LinkedHashMap的有效利用,它的內部存在一個LinkedHashMap成員變數,值得注意的4個方法:構造方法、get、put、trimToSize
LRU(Least Recently Used)快取演算法便應運而生,LRU是最近最少使用的演算法,它的核心思想是當快取滿時,會優先淘汰那些最近最少使用的快取物件。採用LRU演算法的快取有兩種:LrhCache和DisLruCache,分別用於實現記憶體快取和硬碟快取,其核心思想都是LRU快取演算法。
LRU原理
LruCache的核心思想很好理解,就是要維護一個快取物件列表,其中物件列表的排列方式是按照訪問順序實現的,即一直沒訪問的物件,將放在隊尾,即將被淘汰。而最近訪問的物件將放在隊頭,最後被淘汰。
LruCache 其實使用了 LinkedHashMap 雙向連結串列結構,現在分析下 LinkedHashMap 使用方法。
1.構造方法:
public LinkedHashMap(int initialCapacity, float loadFactor, boolean accessOrder) { super(initialCapacity, loadFactor); this.accessOrder = accessOrder; }
當 accessOrder 為 true 時,這個集合的元素順序就會是訪問順序,也就是訪問了之後就會將這個元素放到集合的最後面。
例如:
LinkedHashMap < Integer, Integer > map = new LinkedHashMap < > (0, 0.75f, true); map.put(0, 0); map.put(1, 1); map.put(2, 2); map.put(3, 3); map.get(1); map.get(2); for (Map.Entry < Integer, Integer > entry: map.entrySet()) { System.out.println(entry.getKey() + ":" + entry.getValue()); }
輸出結果:
下面我們在LruCache原始碼中具體看看,怎麼應用LinkedHashMap來實現快取的新增,獲得和刪除的:
/** * @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);//accessOrder被設定為true }
從LruCache的建構函式中可以看到正是用了LinkedHashMap的訪問順序。
2.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++;//插入快取物件加1 size += safeSizeOf(key, value);//增加已有快取的大小 previous = map.put(key, value);//向map中加入快取物件 if (previous != null) {//如果已有快取物件,則快取大小恢復到之前 size -= safeSizeOf(key, previous); } } if (previous != null) {//entryRemoved()是個空方法,可以自行實現 entryRemoved(false, key, previous, value); } trimToSize(maxSize);//調整快取大小(關鍵方法) return previous; }
可以看到put()方法重要的就是在新增過快取物件後,呼叫 trimToSize()方法來保證記憶體不超過maxSize
3.trimToSize方法
再看一下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小於最大快取,或者map為空,不需要再刪除快取物件,跳出迴圈 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); evictionCount++; } entryRemoved(true, key, value, null); } }
trimToSize()方法不斷地刪除LinkedHashMap中隊頭的元素,即近期最少訪問的,直到快取大小小於最大值。
4. get方法
當呼叫LruCache的get()方法獲取集合中的快取物件時,就代表訪問了一次該元素,將會更新佇列,保持整個佇列是按照訪問順序排序。這個更新過程就是在LinkedHashMap中的get()方法中完成的。
接著看LruCache的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) { if (key == null) {//key不能為空 throw new NullPointerException("key == null"); } V mapValue; synchronized (this) { /獲取對應的快取物件 mapValue = map.get(key); if (mapValue != null) { hitCount++; return mapValue; } missCount++; }
看到LruCache的get方法實際是呼叫了LinkedHashMap的get方法:
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; }
再接著看LinkedHashMapEntry的recordAccess方法:
/** * This method is invoked by the superclass whenever the value * of a pre-existing entry is read by Map.get or modified by Map.set. * If the enclosing Map is access-ordered, it moves the entry * to the end of the list; otherwise, it does nothing. */ void recordAccess(HashMap<K,V> m) { LinkedHashMap<K,V> lm = (LinkedHashMap<K,V>)m; if (lm.accessOrder) {//判斷是否是訪問順序 lm.modCount++; remove();//刪除此元素 addBefore(lm.header);//將此元素移到隊尾 } }
recordAccess方法的作用是如果accessOrder為true,把已存在的entry在呼叫get讀取或者set編輯後移到隊尾,否則不做任何操作。
也就是說: 這個方法的作用就是將剛訪問過的元素放到集合的最後一位
5.總結:
LruCache的核心原理就是對LinkedHashMap 物件的有效利用。在構造方法中設定maxSize並將accessOrder設為true,執行get後會將訪問元素放到佇列尾,put操作後則會呼叫trimToSize維護LinkedHashMap的大小不大於maxSize。
參考:https://juejin.im/post/5b5d4e2d6fb9a04fc226c09f ; https://www.cnblogs.com/ganchuanpu/p/8908264.html