Android提供了LRUCache類,可以方便的使用它來實現LRU算法的緩存。Java提供了LinkedHashMap,可以用該類很方便的實現LRU算法,Java的LRULinkedHashMap就是直接繼承了LinkedHashMap,進行了極少的改動后就可以實現LRU算法。
Java的LRU算法的基礎是LinkedHashMap,LinkedHashMap繼承了HashMap,并且在HashMap的基礎上進行了一定的改動,以實現LRU算法。
首先需要說明的是,HashMap將每一個節點信息存儲在Entry
static class Entry<K,V> implements Map.Entry<K,V> { final K key;
V value;
Entry next; int hash; /**
* Creates new entry.
*/ Entry(int h, K k, V v, Entry 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;
} public final boolean equals(Object o) { if (!(o instanceof Map.Entry)) return false;
Map.Entry e = (Map.Entry)o;
Object k1 = getKey();
Object k2 = e.getKey(); if (k1 == k2 || (k1 != null && k1.equals(k2))) {
Object v1 = getValue();
Object v2 = e.getValue(); if (v1 == v2 || (v1 != null && v1.equals(v2))) return true;
} return false;
} public final int hashCode() { return Objects.hashCode(getKey()) ^ Objects.hashCode(getValue());
} public final String toString() { return getKey() + "=" + getValue();
} /**
* This method is invoked whenever the value in an entry is
* overwritten by an invocation of put(k,v) for a key k that's already
* in the HashMap.
*/ void recordAccess(HashMap m) {
} /**
* This method is invoked whenever the entry is
* removed from the table.
*/ void recordRemoval(HashMap m) {
}
}
下面貼一下HashMap的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,計算出hashCode在數組中的位置 int i = indexFor(hash, table.length); //for循環,找到在HashMap中是否存在一個節點,對應的key與傳入的key完全一致。如果存在,說明用戶想要替換該key對應的value值,因此直接替換value即可返回。 for (Entry 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;
}
} //邏輯執行到此處,說明HashMap中不存在完全一致的kye.調用addEntry,新建一個節點保存key、value信息,并增加到HashMap中 modCount++;
addEntry(hash, key, value, i); return null;
}
在上面的代碼中增加了一些注釋,可以對整體有一個了解。下面具體對一些值得分析的點進行說明。
<1> int i = indexFor(hash, table.length);
可以看一下源碼:
static int indexFor(int h, int length) { // assert Integer.bitCount(length) == 1 : "length must be a non-zero power of 2"; return h & (length-1);
}
為什么獲得的hashCode(h)要和(length-1)進行按位與運算?這是為了保證去除掉h的高位信息。如果數組大小為8(1000),而計算出的h的值為10(1010),如果直接獲取數組的index為10的數據,肯定會拋出數組超出界限異常。所以使用按位與(0111&1010),成功清除掉高位信息,得到2(0010),表示對應數組中index為2的數據。效果與取余相同,但是位運算的效率明顯更高。
但是這樣有一個問題,如果length為9,獲取得length-1信息為8(1000),這樣進行位運算,不但不能清除高位數據,得到的結果肯定不對。所以數組的大小一定有什么特別的地方。通過查看源碼,可以發現,HashMap無時無刻不在保證對應的數組個數為2的n次方。
首先在put的時候,調用inflateTable方法。重點在于roundUpToPowerOf2方法,雖然它的內容包含大量的位相關的運算和處理,沒有看的很明白,但是注釋已經明確了,會保證數組的個數為2的n次方。
private void inflateTable(int toSize) { // Find a power of 2 >= 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的n次方。
<2> for (Entry
因為HashMap使用的是數組加鏈表的形式,所以通過hashCode獲取到在數組中的位置后,得到的不是一個Entry
<3> addEntry(hash, key, value, i);
先判斷數組個數是否超出閾值,如果超過,需要增加數組個數。然后會新建一個Entry,并加到數組中。
/**
* Adds a new entry with the specified key, value and hash code to
* the specified bucket. It is the responsibility of this
* method to resize the table if appropriate.
*
* Subclass overrides this to alter the behavior of put method.
*/ 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);
} /**
* Like addEntry except that this version is used when creating entries
* as part of Map construction or "pseudo-construction" (cloning,
* deserialization). This version needn't worry about resizing the table.
*
* Subclass overrides this to alter the behavior of HashMap(Map),
* clone, and readObject.
*/ void createEntry(int hash, K key, V value, int bucketIndex) {
Entry e = table[bucketIndex];
table[bucketIndex] = new Entry<>(hash, key, value, e);
size++;
}
LinkedHashMap在HashMap的基礎上,進行了修改。首先將Entry由單向鏈表改成雙向鏈表。增加了before和after兩個隊Entry的引用。
private static class Entry<K,V> extends HashMap.Entry<K,V> { // These fields comprise the doubly linked list used for iteration. Entry before, after;
Entry(int hash, K key, V value, HashMap.Entry next) { super(hash, key, value, next);
} /**
* Removes this entry from the linked list.
*/ private void remove() {
before.after = after;
after.before = before;
} /**
* Inserts this entry before the specified existing entry in the list.
*/ private void addBefore(Entry existingEntry) {
after = existingEntry;
before = existingEntry.before;
before.after = this;
after.before = this;
} /**
* 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 m) {
LinkedHashMap lm = (LinkedHashMap)m; if (lm.accessOrder) {
lm.modCount++;
remove();
addBefore(lm.header);
}
} void recordRemoval(HashMap m) {
remove();
}
}
同時,LinkedHashMap提供了一個對Entry的引用header(private transient Entry
LinkedHashMap并沒有提供put方法,但是LinkedHashMap重寫了addEntry和createEntry方法,如下:
/**
* This override alters behavior of superclass put method. It causes newly
* allocated entry to get inserted at the end of the linked list and
* removes the eldest entry if appropriate.
*/ void addEntry(int hash, K key, V value, int bucketIndex) {
super.addEntry(hash, key, value, bucketIndex); // Remove eldest entry if instructed Entry eldest = header.after; if (removeEldestEntry(eldest)) {
removeEntryForKey(eldest.key);
}
} /**
* This override differs from addEntry in that it doesn't resize the
* table or remove the eldest entry.
*/ void createEntry(int hash, K key, V value, int bucketIndex) {
HashMap.Entry old = table[bucketIndex];
Entry e = new Entry<>(hash, key, value, old);
table[bucketIndex] = e;
e.addBefore(header);
size++;
}
HashMap的put方法,調用了addEntry方法;HashMap的addEntry方法又調用了createEntry方法。因此可以把上面的兩個方法和HashMap中的內容放到一起,方便分析,形成如下方法:
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 old = table[bucketIndex];
Entry e = new Entry<>(hash, key, value, old);
table[bucketIndex] = e;
e.addBefore(header);
size++; // Remove eldest entry if instructed Entry eldest = header.after; if (removeEldestEntry(eldest)) {
removeEntryForKey(eldest.key);
}
}
同樣,先判斷是否超出閾值,超出則增加數組的個數。然后創建Entry對象,并加入到HashMap對應的數組和鏈表中。與HashMap不同的是LinkedHashMap增加了e.addBefore(header);和removeEntryForKey(eldest.key);這樣兩個操作。
首先分析一下e.addBefore(header)。其中e是LinkedHashMap.Entry對象,addBefore代碼如下,作用就是講header與當前對象相關聯,使當前對象增加到header的雙向鏈表的尾部(header.before):
private void addBefore(Entry existingEntry) {
after = existingEntry;
before = existingEntry.before;
before.after = this;
after.before = this;
}
其次是另一個重點,代碼如下:
// Remove eldest entry if instructed Entry<K,V> eldest = header.after; if (removeEldestEntry(eldest)) {
removeEntryForKey(eldest.key);
}
其中,removeEldestEntry判斷是否需要刪除近不常使用的那個節點。LinkedHashMap中的removeEldestEntry(eldest)方法永遠返回false,如果我們要實現LRU算法,就需要重寫這個方法,判斷在什么情況下,刪除近不常使用的節點。removeEntryForKey的作用就是將key對應的節點在HashMap的數組加鏈表結構中刪除,源碼如下:
final Entry removeEntryForKey(Object key) { if (size == 0) { return null;
} int hash = (key == null) ? 0 : hash(key); int i = indexFor(hash, table.length);
Entry prev = table[i];
Entry e = prev; while (e != null) {
Entry next = e.next;
Object k; if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k)))) {
modCount++;
size--; if (prev == e)
table[i] = next; else prev.next = next;
e.recordRemoval(this); return e;
}
prev = e;
e = next;
} return e;
}
removeEntryForKey是HashMap的方法,對LinkedHashMap中header的雙向鏈表無能為力,而LinkedHashMap又沒有重寫這個方法,那header的雙向鏈表要如何處理呢。
仔細看一下代碼,可以看到在成功刪除了HashMap中的節點后,調用了e.recordRemoval(this);方法。這個方法在HashMap中為空,LinkedHashMap的Entry則實現了這個方法。其中remove()方法中的兩行代碼為雙向鏈表中刪除當前節點的標準代碼,不解釋。
/**
* Removes this entry from the linked list.
*/ private void remove() {
before.after = after;
after.before = before;
}void recordRemoval(HashMap m) {
remove();
}
以上,LinkedHashMap增加節點的代碼分析完畢,可以看到完美的將新增的節點放在了header雙向鏈表的末尾。
但是,這樣顯然是先進先出的算法,而不是近不常使用算法。需要在get的時候,更新header雙向鏈表,把剛剛get的節點放到header雙向鏈表的末尾。我們來看看get的源碼:
public V get(Object key) {
Entry e = (Entry)getEntry(key); if (e == null) return null;
e.recordAccess(this); return e.value;
}
代碼很短,行的getEntry調用的是HashMap的getEntry方法,不需要解釋。真正處理header雙向鏈表的代碼是e.recordAccess(this)。看一下代碼:
/**
* Removes this entry from the linked list.
*/ private void remove() {
before.after = after;
after.before = before;
} /**
* Inserts this entry before the specified existing entry in the list.
*/ private void addBefore(Entry existingEntry) {
after = existingEntry;
before = existingEntry.before;
before.after = this;
after.before = this;
} /**
* 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 m) {
LinkedHashMap lm = (LinkedHashMap)m; if (lm.accessOrder) {
lm.modCount++;
remove();
addBefore(lm.header);
}
}
首先在header雙向鏈表中刪除當前節點,再將當前節點添加到header雙向鏈表的末尾。當然,在調用LinkedHashMap的時候,需要將accessOrder設置為true,否則就是FIFO算法。
Android同樣提供了HashMap和LinkedHashMap,而且總體思路有些類似,但是實現的細節明顯不同。而且Android提供的LruCache雖然使用了LinkedHashMap,但是實現的思路并不一樣。Java需要重寫removeEldestEntry來判斷是否刪除節點;而Android需要重寫LruCache的sizeOf,返回當前節點的大小,Android會根據這個大小判斷是否超出了限制,進行調用trimToSize方法清除多余的節點。
Android的sizeOf方法默認返回1,默認的方式是判斷HashMap中的數據個數是否超出了設置的閾值。也可以重寫sizeOf方法,返回當前節點的大小。Android的safeSizeOf會調用sizeOf方法,其他判斷閾值的方法會調用safeSizeOf方法,進行加減操作并判斷閾值。進而判斷是否需要清除節點。
Java的removeEldestEntry方法,也可以達到同樣的效果。Java需要使用者自己提供整個判斷的過程,兩者思路還是有些區別的。
sizeOf,safeSizeOf不需要說明,而put和get方法,雖然和Java的實現方式不完全一樣,但是思路是相同的,也不需要分析。在LruCache中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);
}
}
重點需要說明的是Map.Entry toEvict = (Map.Entry)this.map.entrySet().iterator().next();這行代碼。它前面的代碼判斷是否需要刪除近不常使用的節點,后面的代碼用于刪除具體的節點。這行代碼用于獲取近不常使用的節點。
首先需要說明的問題是,Android的LinkedHashMap和Java的LinkedHashMap在思路上一樣,也是使用header保存雙向鏈表。在put和get的時候,會更新對應的節點,保存header.after指向久沒有使用的節點;header.before用于指向剛剛使用過的節點。所以Map.Entry toEvict = (Map.Entry)this.map.entrySet().iterator().next();這行終肯定是獲取header.after節點。下面逐步分析代碼,就可以看到是如何實現的了。
首先,map.entrySet(),HashMap定義了這個方法,LinkedHashMap沒有重寫這個方法。因此調用的是HashMap對應的方法:
public Set> entrySet() { Set> es = entrySet; return (es != null) ? es : (entrySet = new EntrySet());
}
上面代碼不需要細說,new一個EntrySet類的實例。而EntrySet也是在HashMap中定義,LinkedHashMap中沒有。
private final class EntrySet extends AbstractSet<Entry<K, V>> { public Iterator> iterator() { return newEntryIterator();
} public boolean contains(Object o) { if (!(o instanceof Entry)) return false;
Entry e = (Entry) o; return containsMapping(e.getKey(), e.getValue());
} public boolean remove(Object o) { if (!(o instanceof Entry)) return false;
Entry e = (Entry)o; return removeMapping(e.getKey(), e.getValue());
} public int size() { return size;
} public boolean isEmpty() { return size == 0;
} public void clear() {
HashMap.this.clear();
}
}
Iterator> newEntryIterator() { return new EntryIterator(); }
代碼中很明顯的可以看出,Map.Entry toEvict = (Map.Entry)this.map.entrySet().iterator().next(),就是要調用newEntryIterator().next(),就是調用(new EntryIterator()).next()。而EntryIterator類在LinkedHashMap中是有定義的。
private final class EntryIterator extends LinkedHashIterator<Map.Entry<K, V>> { public final Map.Entry next() { return nextEntry(); }
} private abstract class LinkedHashIterator<T> implements Iterator<T> {
LinkedEntry next = header.nxt;
LinkedEntry lastReturned = null; int expectedModCount = modCount; public final boolean hasNext() { return next != header;
} final LinkedEntry nextEntry() { if (modCount != expectedModCount) throw new ConcurrentModificationException();
LinkedEntry e = next; if (e == header) throw new NoSuchElementException();
next = e.nxt; return lastReturned = e;
} public final void remove() { if (modCount != expectedModCount) throw new ConcurrentModificationException(); if (lastReturned == null) throw new IllegalStateException();
LinkedHashMap.this.remove(lastReturned.key);
lastReturned = null;
expectedModCount = modCount;
}
}
現在可以得到結論,trimToSize中的那行代碼得到的就是header.next對應的節點,也就是近不常使用的那個節點。
本站文章版權歸原作者及原出處所有 。內容為作者個人觀點, 并不代表本站贊同其觀點和對其真實性負責,本站只提供參考并不構成任何投資及應用建議。本站是一個個人學習交流的平臺,網站上部分文章為轉載,并不用于任何商業目的,我們已經盡可能的對作者和來源進行了通告,但是能力有限或疏忽,造成漏登,請及時聯系我們,我們將根據著作權人的要求,立即更正或者刪除有關內容。本站擁有對此聲明的最終解釋權。