先来看看给我印象深刻的Lrucache中的关键代码。
//得到图片大小需覆写的方法
protected int sizeOf(K key, V value) {
return 1;
//返回图片也就是value的占用内存的大小
}
// 第三个是关键性参数,true的话,map在get操作的时候,如果返回不为空的话,会将当前节点移到最前端
this.map = new LinkedHashMap<K, V>(0, 0.75f, true);
LinkedHashMap源码:
if (accessOrder)
makeTail((LinkedEntry<K, V>) e);
return e.value;
/**
* Relinks the given entry to the tail of the list. Under access ordering,
* this method is invoked whenever the value of a pre-existing entry is
* read by Map.get or modified by Map.put.
*/
private void makeTail(LinkedEntry<K, V> e) {
// Unlink e
e.prv.nxt = e.nxt;
e.nxt.prv = e.prv;
// Relink e as tail
LinkedEntry<K, V> header = this.header;
LinkedEntry<K, V> oldTail = header.prv;
e.nxt = header;
e.prv = oldTail;
oldTail.nxt = header.prv = e;
modCount++;
}
一直以来困惑我的问题在于Lrucache在get的时候,返回不为空的时候,是怎么实现的让当前节点移动到链表map的最前端,今天看源码的时候得到了解答。
然后Lrucache每次put操作时都会安全检查一下。当超出时,则:
Map.Entry<K, V> toEvict = map.entrySet().iterator().next();
key = toEvict.getKey();
value = toEvict.getValue();
map.remove(key);
size -= safeSizeOf(key, value);
差不多了,这就是我对LruCache是怎么实现LRU算法,并且能保证内存不溢出的理解!!!