LinkedHashMap 对 HashMap 功能进行了扩展,它通常被用在 LRU 的场景中,对于元素的插入和删除操作,实现上完全来自于 HashMap,其主要是重写了 HashMap 中提供的可扩展的方法 afterNodeAccess、afterNodeInsertion 和 afterNodeRemoval,因此本篇我们重点看这三个方法,插入和删除的基本操作的实现,可参考本系列的 HashMap 篇。
1. 重要属性及构造方法
/**
* HashMap.Node subclass for normal LinkedHashMap entries.
*/
// Entry 扩展了 HashMap 中的 Node,增加了 before 和 after 属性,
// 这两个属性构成了双向链表
static class Entry<K,V> extends HashMap.Node<K,V> {
Entry<K,V> before, after;
Entry(int hash, K key, V value, Node<K,V> next) {
super(hash, key, value, next);
}
}
/**
* The head (eldest) of the doubly linked list.
*/
// 双向链表的头节点,最旧的被访问过的节点
transient LinkedHashMap.Entry<K,V> head;
/**
* The tail (youngest) of the doubly linked list.
*/
// 双向链表的尾节点,最新的被访问过的节点
transient LinkedHashMap.Entry<K,V> tail;
/**
* The iteration ordering method for this linked hash map: <tt>true</tt>
* for access-order, <tt>false</tt> for insertion-order.
*
* @serial
*/
// 迭代顺序,true 表示按照被访问的时间顺序,false 表示按照插入顺序,
// 默认为 false
final boolean accessOrder;
/**
* Constructs an empty insertion-ordered <tt>LinkedHashMap</tt> instance
* with the default initial capacity (16) and load factor (0.75).
*/
public LinkedHashMap() {
super();
// accessOrder 默认值为 false,
accessOrder = false;
}
2. put()
public V put(K key, V value) {
return putVal(hash(key), key, value, false, true);
}
putVal()
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)
// 插入新的节点时,会将新节点加入 LRU 队列的尾部
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) {
// 插入新的节点时,会将新节点从 LRU 链表的尾部加入
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;
// 修改现有 key 对应的 value,等同于一次访问操作,触发后置处理
afterNodeAccess(e);
return oldValue;
}
}
++modCount;
// 扩容
if (++size > threshold)
resize();
// 插入操作的后置处理,evict 默认 true
afterNodeInsertion(evict);
return null;
}
newNode()
Node<K,V> newNode(int hash, K key, V value, Node<K,V> e) {
LinkedHashMap.Entry<K,V> p =
new LinkedHashMap.Entry<K,V>(hash, key, value, e);
// 新构造的节点,从 LRU 链表的尾部加入
linkNodeLast(p);
return p;
}
private void linkNodeLast(LinkedHashMap.Entry<K,V> p) {
LinkedHashMap.Entry<K,V> last = tail;
tail = p;
if (last == null)
head = p;
else {
p.before = last;
last.after = p;
}
}
afterNodeAccess()
void afterNodeAccess(Node<K,V> e) { // move node to last
LinkedHashMap.Entry<K,V> last;
// accessOrder 默认值为 false,默认情况下条件不成立。
// accessOrder 设置为 true 时,当 node 被访问,会将其加入双向链表的尾部,
// 表示最新被访问过的节点
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;
}
}
afterNodeInsertion()
void afterNodeInsertion(boolean evict) { // possibly remove eldest
LinkedHashMap.Entry<K,V> first;
// 插入操作执行后,执行删除的操作,LinkedHashMap 默认的实现中,
// removeEldestEntry() 方法默认返回 false,即不进行删除。
// 同时 removeEldestEntry() 方法被设计成 protected 关键字修饰,
// 这里是将移除的条件交给用户自己去实现,因此我们在使用 LHM 作为 LRU 容器时,
// 需要重写 removeEldestEntry() 方法来定义触发淘汰的条件。
if (evict && (first = head) != null && removeEldestEntry(first)) {
K key = first.key;
// removeNode() 方法的详细说明见下面的 remove() 方法章节
removeNode(hash(key), key, null, false, true);
}
}
3. remove()
public V remove(Object key) {
Node<K,V> e;
return (e = removeNode(hash(key), key, null, false, true)) == null ?
null : e.value;
}
removeNode()
final Node<K,V> removeNode(int hash, Object key, Object value,
boolean matchValue, boolean movable) {
Node<K,V>[] tab; Node<K,V> p; int n, index;
if ((tab = table) != null && (n = tab.length) > 0 &&
(p = tab[index = (n - 1) & hash]) != null) {
Node<K,V> node = null, e; K k; V v;
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
node = p;
else if ((e = p.next) != null) {
if (p instanceof TreeNode)
node = ((TreeNode<K,V>)p).getTreeNode(hash, key);
else {
do {
if (e.hash == hash &&
((k = e.key) == key ||
(key != null && key.equals(k)))) {
node = e;
break;
}
p = e;
} while ((e = e.next) != null);
}
}
if (node != null && (!matchValue || (v = node.value) == value ||
(value != null && value.equals(v)))) {
if (node instanceof TreeNode)
((TreeNode<K,V>)node).removeTreeNode(this, tab, movable);
else if (node == p)
tab[index] = node.next;
else
p.next = node.next;
++modCount;
--size;
// 移除成功,触发后置操作
afterNodeRemoval(node);
return node;
}
}
return null;
}
afterNodeRemoval()
void afterNodeRemoval(Node<K,V> e) { // unlink
// 节点从容器中删除成功后,要从 LRU 链表中移除
LinkedHashMap.Entry<K,V> p =
(LinkedHashMap.Entry<K,V>)e, b = p.before, a = p.after;
p.before = p.after = null;
if (b == null)
head = a;
else
b.after = a;
if (a == null)
tail = b;
else
a.before = b;
}
3. get()
public V get(Object key) {
Node<K,V> e;
if ((e = getNode(hash(key), key)) == null)
return null;
// 如果迭代顺序是按照节点被访问的时间顺序,
// 当节点被访问后,需要更新 LRU 链表
if (accessOrder)
afterNodeAccess(e);
return e.value;
}
afterNodeAccess()
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;
}
}
4. 总结
- LinkedHashMap 内部使用双向链表来维护按时间排序的最近被访问的节点,链表头部表示最旧被访问过(或插入)的节点,尾部表示最新被访问(或插入)的节点。
- LinkedHashMap 通过 accessOrder 属性控制 LRU 链表的组织方式,accessOrder 为真表示元素被访问(包括查询和插入)时更新 LRU 链表,为假表示只在元素被插入时才更新 LRU 链表。accessOrder 默认为 false。
- LinkedHashMap 中默认不触发淘汰,用户需要重写 removeEldestEntry() 方法来定义触发淘汰的条件。
- 使用示例。下面的示例来自于 com.mysql.jdbc.util.LRUCache:
public class LRUCache<K, V> extends LinkedHashMap<K, V> {
private static final long serialVersionUID = 1L;
protected int maxElements;
public LRUCache(int maxSize) {
super(maxSize, 0.75F, true);
this.maxElements = maxSize;
}
protected boolean removeEldestEntry(Entry<K, V> eldest) {
return this.size() > this.maxElements;
}
}