以铜为镜,可以正衣冠;以史为镜,可以知更替 --题记
学习一个技术,我们需要带着what,why,how的思路去探索
关于缓存淘汰算法 LRU,它的核心思想是最近使用的数据,后面使用的概率也很大,这个适合一些我们需要缓存数据的场景,实现的方式有很多种,我们站在巨人(Josh Bloch)的肩膀上谈谈如何基LinkedHashMap去实现
首先实现 LRU 算法,我们需要提供两个基本操作 API,get,put 方法
基于LinkedHashMap已经实现好的数据结构,我们需要做的事情并不多了,但仍然需要我们先考虑二种情况,这也是实现 LRU 算法的核心思路
一、访问节点情况:访问的节点移动到双向链表尾部表示活跃节点
二、存入节点时超过容量情况:通过移除双向链表最前端的节点
我们先来看下面的实现方案
class LRUCache extends LinkedHashMap<Integer,Integer> {
private int capacity;
public LRUCache(int capacity) {
super(capacity, 0.75f, true);
this.capacity = capacity;
}
public int get(int key) {
//访问的节点移动到双向链表尾部表示活跃节点
return super.getOrDefault(key, -1);
}
public void put(int key, int value) {
super.put(key, value);
}
@Override
protected boolean removeEldestEntry(Map.Entry eldest) {
return size() > capacity;
}
}
实现方案很简单,但是我们需要知道LinkedHashMap为我们做了些什么事情,现在我们来解析下它的实现
get方法:调用父类LinkedHashMap的getOrDefault方法,获取不到值返回-1默认值
public V getOrDefault(Object key, V defaultValue) {
Node<K,V> e;
if ((e = getNode(hash(key), key)) == null)
return defaultValue;
if (accessOrder)
afterNodeAccess(e);
return e.value;
}
看不懂下面这段代码也没关系,只需要知道这段代码做了一件什么事情,那就是把访问的节点放到了双向链表的尾部,表示最近访问的活跃节点,确保accessOrder为true,我们在LRUCache的构造函数中初始化了
void afterNodeAccess(Node<K,V> e) { // move node to last
LinkedHashMap.Entry<K,V> last;
if (accessOrder && (last = tail) != e) {
LinkedHashMap.Entry<K,V> p =
(LinkedHashMap.Entry<K,V>)e, b = p.before, a = p.after;
p.after = null;
if (b == null)
head = a;
else
b.after = a;
if (a != null)
a.before = b;
else
last = b;
if (last == null)
head = p;
else {
p.before = last;
last.after = p;
}
tail = p;
++modCount;
}
}
到这里我们就明确了我们前面所说的第一种情况:访问的节点移动到双向链表尾部表示活跃节点
HashMap的put方法
final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
boolean evict) {
Node<K,V>[] tab; Node<K,V> p; int n, i;
if ((tab = table) == null || (n = tab.length) == 0)
n = (tab = resize()).length;
if ((p = tab[i = (n - 1) & hash]) == null)
tab[i] = newNode(hash, key, value, null);
else {
Node<K,V> e; K k;
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
e = p;
else if (p instanceof TreeNode)
e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
else {
for (int binCount = 0; ; ++binCount) {
if ((e = p.next) == null) {
p.next = newNode(hash, key, value, null);
if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
treeifyBin(tab, hash);
break;
}
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
break;
p = e;
}
}
if (e != null) { // existing mapping for key
V oldValue = e.value;
if (!onlyIfAbsent || oldValue == null)
e.value = value;
afterNodeAccess(e);
return oldValue;
}
}
++modCount;
if (++size > threshold)
resize();
//重点关注
afterNodeInsertion(evict);
return null;
}
看到这段先不要着急,因为我们关注的重点也就一个方法afterNodeInsertion(evict);
void afterNodeInsertion(boolean evict) { // possibly remove eldest
LinkedHashMap.Entry<K,V> first;
if (evict && (first = head) != null && removeEldestEntry(first)) {
K key = first.key;
removeNode(hash(key), key, null, false, true);
}
}
afterNodeInsertion函数是HashMap的钩子函数,具体实现由Josh Bloch实现的LinkedHashMap实现了,我们需要覆写的是removeEldestEntry函数,即前面所说的第二种情况,存入节点时超过容量情况:通过移除双向链表最前端的节点,通过first = head我们可以看出移除的是头节点
总结:
1、基于LinkedHashMap的特性,我们的LRU算法是以尾节点为最近访问节点,即热节点,头节点为最久未访问节点,容量满时最先移除
2、LinkedHashMap实现基于HashMap,较为复杂,我们重点关注LRU算法的思路
| move node to last | possibly remove eldest |