如何通過linkedhashmap實現高速緩存?
要求:存儲特定個數的熱點數據,不常訪問的數據自動刪除掉.
只需要:自定義LinkedHashMap的匿名子類,重寫removeEldestEntry方法.
LinkedHashMap<Object, Object> map = new LinkedHashMap<Object, Object>(5, 0.75F,
true) {
@Override//重寫的這個方法會在調用afterNodeInsertion方法時被使用到.
protected boolean removeEldestEntry(Entry eldest) {
return size() > 5;
}
};
map.put(1, 1);
map.put(2, 2);
map.put(3, 3);
map.put(4, 4);
Object o = map.get(2);
map.put(5, 5);
map.put(6, 6);
Set<Object> objects = map.keySet();
objects.forEach(e -> System.out.print(e + " "));
System.out.println();
map.values().forEach(e -> System.out.print(e + " "));
//控制檯輸出
3 4 2 5 6
3 4 2 5 6
2放到了"末尾",1被"頂出".
常用的數據會一直在尾部
源碼解釋:
hashmap的put方法會調用afterNodeInsertion方法,afterNodeInsertion方法中會用到removeEldestEntry方法進行判斷.所以需要重寫這個方法.
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;
}
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);
}
}