Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Java 與 Android 的 LRU 快取:從原始碼看實作原理

編輯:關於 Android 程式設計

一、概要

Android 直接提供了 LruCache,拿來就能用;Java 這邊則提供 LinkedHashMap,只要繼承它並做極少量改動,就是一個現成的 LRU 容器。兩者的思路相似,但細節差異不小,下面從 HashMap 一路拆到 LruCache。

二、Java 的 LRU 實作

1. HashMap

HashMap 把每筆資料包成 Entry<K,V>,裡面存著 key、value、hash,以及指向下一個節點的參照——也就是說 Entry 構成的是單向鏈結串列。整體結構是「陣列 + 單向鏈結串列」:先用 key 的 hashCode 定位陣列槽位,若多個 key 落在同一槽,就串成鏈結串列挂在該槽上。

 static class Entry<K,V> implements Map.Entry<K,V> { final K key; V value; Entry<K,V> next; int hash; Entry(int h, K k, V v, Entry<K,V> n) { value = v; next = n; key = k; hash = h; } public final K getKey() { return key; } public final V getValue() { return value; } public final V setValue(V newValue) { V oldValue = value; value = newValue; return oldValue; } void recordAccess(HashMap<K,V> m) { } void recordRemoval(HashMap<K,V> m) { } }

接著看 put,我在關鍵處補了註解:

 public V put(K key, V value) { if (table == EMPTY_TABLE) { inflateTable(threshold); } if (key == null) return putForNullKey(value); // 先算出 hashCode int hash = hash(key); // 再把 hashCode 映射成陣列索引 int i = indexFor(hash, table.length); // 沿鏈走訪,若已存在相同 key,直接換掉 value for (Entry<K,V> e = table[i]; e != null; e = e.next) { Object k; if (e.hash == hash && ((k = e.key) == key || key.equals(k))) { V oldValue = e.value; e.value = value; e.recordAccess(this); return oldValue; } } // 走到這裡代表沒有重複 key,新建節點 modCount++; addEntry(hash, key, value, i); return null; }

值得展開的幾處:

<1> 為什麼是 h & (length-1) 而不是取餘數?

 static int indexFor(int h, int length) { return h & (length-1); }

這麼做是為了砍掉 hashCode 的高位。假設陣列長度為 8(1000),算出來的 h 是 10(1010),若直接拿 10 當索引必定越界;而 1010 & 0111 = 0010,高位被清掉,結果是 2。效果等同取餘,但位元運算的效能更好。

問題是這個技巧只有在 length 為 2 的 n 次方時才成立。若 length 是 9,length-1 為 1000,反而無法清高位。所以 HashMap 時時刻刻都在維持「容量為 2 的 n 次方」這個不變式:

 private void inflateTable(int toSize) { int capacity = roundUpToPowerOf2(toSize); threshold = (int) Math.min(capacity * loadFactor, MAXIMUM_CAPACITY + 1); table = new Entry[capacity]; initHashSeedAsNeeded(capacity); }

在 addEntry 等位置也會用 2 * table.length、table.length << 1 之類的寫法持續維持這個特性。

<2> 為什麼拿到的是鏈而非單一節點

因為同一槽可能掛著多個 Entry,所以必須沿 next 走訪,才能找到 key 真正對應的 value。

<3> addEntry 做了什麼

先檢查是否達到閾值,必要時擴容,再建立新節點掛進去:

 void addEntry(int hash, K key, V value, int bucketIndex) { if ((size >= threshold) && (null != table[bucketIndex])) { resize(2 * table.length); hash = (null != key) ? hash(key) : 0; bucketIndex = indexFor(hash, table.length); } createEntry(hash, key, value, bucketIndex); } void createEntry(int hash, K key, V value, int bucketIndex) { Entry<K,V> e = table[bucketIndex]; table[bucketIndex] = new Entry<>(hash, key, value, e); size++; }

2. LinkedHashMap

LinkedHashMap 在 HashMap 之上做了兩件事:把 Entry 從單向鏈改成雙向鏈(多出 before、after 兩個參照),並額外維護一個 header 節點作為這條雙向鏈的固定頭尾。

 private static class Entry<K,V> extends HashMap.Entry<K,V> { Entry<K,V> before, after; Entry(int hash, K key, V value, HashMap.Entry<K,V> next) { super(hash, key, value, next); } private void remove() { before.after = after; after.before = before; } private void addBefore(Entry<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(); } }

也就是說,LinkedHashMap 同時保留了 HashMap 的「陣列 + 鏈」索引結構,又額外維護一條以 header 為哨兵的雙向鏈。其中 header.after 永遠指向最久未被使用的那筆,要淘汰就砍它;header.before 則是最近剛被使用的那筆。

LinkedHashMap 沒有重寫 put,而是改寫了 addEntry 與 createEntry:

 void addEntry(int hash, K key, V value, int bucketIndex) { super.addEntry(hash, key, value, bucketIndex); Entry<K,V> eldest = header.after; if (removeEldestEntry(eldest)) { removeEntryForKey(eldest.key); } } void createEntry(int hash, K key, V value, int bucketIndex) { HashMap.Entry<K,V> old = table[bucketIndex]; Entry<K,V> e = new Entry<>(hash, key, value, old); table[bucketIndex] = e; e.addBefore(header); size++; }

把父子兩代的方法合併來看更清楚:

 void addEntry(int hash, K key, V value, int bucketIndex) { if ((size >= threshold) && (null != table[bucketIndex])) { resize(2 * table.length); hash = (null != key) ? hash(key) : 0; bucketIndex = indexFor(hash, table.length); } HashMap.Entry<K,V> old = table[bucketIndex]; Entry<K,V> e = new Entry<>(hash, key, value, old); table[bucketIndex] = e; e.addBefore(header); size++; Entry<K,V> eldest = header.after; if (removeEldestEntry(eldest)) { removeEntryForKey(eldest.key); } }

與 HashMap 相比,多了 e.addBefore(header)(把新節點掛到雙向鏈尾端)以及後面的淘汰判斷。而 removeEntryForKey 是 HashMap 的方法,它只認得陣列與 next 鏈,那雙向鏈怎麼辦?答案藏在刪除成功後呼叫的 e.recordRemoval(this):

 private void remove() { before.after = after; after.before = before; } void recordRemoval(HashMap<K,V> m) { remove(); }

HashMap 裡這個方法是空的,LinkedHashMap 的 Entry 則把它實作掉,兩行就是雙向鏈刪節點的標準寫法。

不過若只做到這裡,那是 FIFO 而非 LRU。要變成 LRU,得在讀取時把該節點挪回鏈尾,這由 get 觸發:

 public V get(Object key) { Entry<K,V> e = (Entry<K,V>)getEntry(key); if (e == null) return null; e.recordAccess(this); return e.value; }
 void recordAccess(HashMap<K,V> m) { LinkedHashMap<K,V> lm = (LinkedHashMap<K,V>)m; if (lm.accessOrder) { lm.modCount++; remove(); addBefore(lm.header); } }

先從鏈中摘掉,再接到鏈尾。前提是建立 LinkedHashMap 時要把 accessOrder 設為 true,否則拿到的就是插入序(FIFO)。

三、Android 的 LRU 實作

Android 的 LruCache 內部同樣使用 LinkedHashMap,但淘汰策略的控制點不同:Java 需要你覆寫 removeEldestEntry 自行決定何時淘汰;Android 則是覆寫 sizeOf,回報每筆資料的「大小」,再由框架加總後與上限比較,超過就呼叫 trimToSize 清理。

sizeOf 預設回傳 1,也就是以「筆數」為單位計算;改寫它之後就能以位元組數等維度計量。safeSizeOf 會包一層去呼叫 sizeOf,其餘判斷閾值的地方都走 safeSizeOf。

put 的最後會呼叫 trimToSize,它是真正動手淘汰的地方:

 public void trimToSize(int maxSize) { while (true) { Object key; Object value; synchronized (this) { if ((this.size < 0) || ((this.map.isEmpty()) && (this.size != 0))) { throw new IllegalStateException(getClass().getName() + ".sizeOf() is reporting inconsistent results!"); } if (size <= maxSize) { break; } Map.Entry toEvict = (Map.Entry)this.map.entrySet().iterator().next(); key = toEvict.getKey(); value = toEvict.getValue(); this.map.remove(key); this.size -= safeSizeOf(key, value); this.evictionCount += 1; } entryRemoved(true, key, value, null); } }

關鍵那行是 this.map.entrySet().iterator().next()——它拿到的究竟是「最久未使用」的那筆嗎?逐層拆開來看。

首先 entrySet() 定義在 HashMap,LinkedHashMap 並未覆寫:

 public Set<Entry<K, V>> entrySet() { Set<Entry<K, V>> es = entrySet; return (es != null) ? es : (entrySet = new EntrySet()); }

它會 new 一個 EntrySet,而 EntrySet 的 iterator 走的是 newEntryIterator():

 private final class EntrySet extends AbstractSet<Entry<K, V>> { public Iterator<Entry<K, V>> iterator() { return newEntryIterator(); } public int size() { return size; } } Iterator<Entry<K, V>> newEntryIterator() { return new EntryIterator(); }

EntryIterator 則定義在 LinkedHashMap 境內,它的 next 實求是委派給 LinkedHashIterator:

 private final class EntryIterator extends LinkedHashIterator<Map.Entry<K, V>> { public final Map.Entry<K, V> next() { return nextEntry(); } } private abstract class LinkedHashIterator<T> implements Iterator<T> { LinkedEntry<K, V> next = header.nxt; LinkedEntry<K, V> lastReturned = null; int expectedModCount = modCount; public final boolean hasNext() { return next != header; } final LinkedEntry<K, V> nextEntry() { if (modCount != expectedModCount) throw new ConcurrentModificationException(); LinkedEntry<K, V> e = next; if (e == header) throw new NoSuchElementException(); next = e.nxt; return lastReturned = e; } }

注意初始值:next = header.nxt。而 header 之後的第一個節點,正是前面提到的「最久未使用」那筆。結論就此成立:trimToSize 拿到的確實是 LRU 目標。

總結一句:Java 讓你自己實作淘汰條件(removeEldestEntry),Android 把計量交給 sizeOf、把淘汰交給 trimToSize, Responsibilities 切法不同,但底層依賴的都是那條以 header 為哨兵的雙向鏈。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved