gau*_*ain 8 java android linkedhashmap android-lru-cache
我检查了LRUCache的官方Android文档,其中说:每次访问一个值时,它都会移动到队列的头部.将值添加到完整缓存时,该队列末尾的值将被逐出,并且可能符合垃圾回收的条件.我想这是双链表,它由缓存使用的linkedhashmap维护.为了检查这种行为,我检查了LruCache的源代码,并检查了get(K key)方法.它进一步调用map的get方法,该方法从底层hashmap获取值并调用recordAccess方法.
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;
}
Run Code Online (Sandbox Code Playgroud)
如果accessOrder设置为true(对于我的问题,我们假设它是),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);
}
}
Run Code Online (Sandbox Code Playgroud)
这听起来与上面的陈述相矛盾,其中说元素被移动到队列的头部.相反,它被移动到列表的最后一个元素(使用head.before).当然,我在这里错过了什么,有什么帮助吗?
您没有错过任何内容,只是您正在LruCache阅读LinkedHashMap. LinkedHashMap有自己的文档,特别是关于其accessOrder. ( Java 文档也是如此)。
[...when accessOrder=true...] 迭代顺序是其条目最后被访问的顺序,从最近最少访问到最近访问(访问顺序)
因此,LinkedHashMap将最近使用的条目放在最后,并记录下来。
实际上LruCache描述了这种缓存在理论上是如何工作的,但LinkedHashMap展示了如何在不添加单独的向后移动迭代器的情况下实现它:通过将最近的元素放在末尾,修剪可以使用已经可用的(向前移动)迭代器来访问(和删除)有效地处理旧元素。
虽然此时此地我无法判断出了什么问题removeEldestEntry。也许过去并不存在。
| 归档时间: |
|
| 查看次数: |
424 次 |
| 最近记录: |