LinkedHashMap源码分析
一、简介
LinkedHashMap继承了HashMap,并通过双向列表来维护元素的顺序,本文结合HashMap的源码探究一下LinkedHashMap是如何维护元素的顺序的。
1.1 构造方法
public class LinkedHashMap<K,V> extends HashMap<K,V> implements Map<K,V> {
/**
* The iteration ordering method for this linked hash map: <tt>true</tt>
* for access-order, <tt>false</tt> for insertion-order.
*
* @serial
*/
final boolean accessOrder;
/**
* Constructs an empty insertion-ordered <tt>LinkedHashMap</tt> instance
* with the specified initial capacity and load factor.
*
* @param initialCapacity the initial capacity
* @param loadFactor the load factor
* @throws IllegalArgumentException if the initial capacity is negative
* or the load factor is nonpositive
*/
public LinkedHashMap(int initialCapacity, float loadFactor) {
super(initialCapacity, loadFactor);
accessOrder = false;
}
/**
* Constructs an empty insertion-ordered <tt>LinkedHashMap</tt> instance
* with the specified initial capacity and a default load factor (0.75).
*
* @param initialCapacity the initial capacity
* @throws IllegalArgumentException if the initial capacity is negative
*/
public LinkedHashMap(int initialCapacity) {
super(initialCapacity);
accessOrder = false;
}
/**
* 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;
}
/**
* Constructs an insertion-ordered <tt>LinkedHashMap</tt> instance with
* the same mappings as the specified map. The <tt>LinkedHashMap</tt>
* instance is created with a default load factor (0.75) and an initial
* capacity sufficient to hold the mappings in the specified map.
*
* @param m the map whose mappings are to be placed in this map
* @throws NullPointerException if the specified map is null
*/
public LinkedHashMap(Map<? extends K, ? extends V> m) {
super();
accessOrder = false;
putMapEntries(m, false);
}
/**
* Constructs an empty <tt>LinkedHashMap</tt> instance with the
* specified initial capacity, load factor and ordering mode.
*
* @param initialCapacity the initial capacity
* @param loadFactor the load factor
* @param accessOrder the ordering mode - <tt>true</tt> for
* access-order, <tt>false</tt> for insertion-order
* @throws IllegalArgumentException if the initial capacity is negative
* or the load factor is nonpositive
*/
public LinkedHashMap(int initialCapacity,
float loadFactor,
boolean accessOrder) {
super(initialCapacity, loadFactor);
this.accessOrder = accessOrder;
}
}
LinkedHashMap的构造方法和HashMap相比多了一个accessOrder参数,LinkedHashMap基于双向列表来记录元素的顺序。元素的排序方式根据accessOrder参数来进行控制:
- accessOrder = false :根据元素的插入顺序排序
- accessOrder = true : 根据元素的访问顺序排序
1.2 主要属性
/**
* HashMap.Node subclass for normal LinkedHashMap entries.
*/
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);
}
}
private static final long serialVersionUID = 3801124242820219131L;
/**
* 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
*/
final boolean accessOrder;
- LinkedHashMap的静态内部类
Entry<K,V>
继承了HashMap的HashMap.Node<K,V>
,Entry
内部新增了before和after两个属性,实现了双向列表。 head
和tail
两个字段用于记录队列的头节点和尾节点。accessOrder
控制列表的顺序是根据插入顺序排序还是根据访问顺序进行排序。1.3 主要方法
LinkedHashMap并没有重写父类HashMap的put方法,而是重写了HashMap中空的钩子方法,HashMap源码如下:
这些钩子方法在HashMap的// Callbacks to allow LinkedHashMap post-actions void afterNodeAccess(Node<K,V> p) { } void afterNodeInsertion(boolean evict) { } void afterNodeRemoval(Node<K,V> p) { }
put
等方法中进行了调用,如:public V put(K key, V value) { return putVal(hash(key), key, value, false, true); } 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(boolean evict)方法
这个方法的主要作用就是在元素添加到Map中后,判断是否要移除最老的元素,默认返回false。
我们来看一下removeEldestEntry(first)方法的实现: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); } }
当我们将LinkedHashMap用作LRU缓存,我们需要限制缓存的大小,这时我们需要重写LinkedHashMap的removeEldestEntry方法,当元素个数超过设置的最大值后,则移除最老的元素,代码如下:/** * Returns <tt>true</tt> if this map should remove its eldest entry. * This method is invoked by <tt>put</tt> and <tt>putAll</tt> after * inserting a new entry into the map. It provides the implementor * with the opportunity to remove the eldest entry each time a new one * is added. This is useful if the map represents a cache: it allows * the map to reduce memory consumption by deleting stale entries. * * <p>Sample use: this override will allow the map to grow up to 100 * entries and then delete the eldest entry each time a new entry is * added, maintaining a steady state of 100 entries. * <pre> * private static final int MAX_ENTRIES = 100; * * protected boolean removeEldestEntry(Map.Entry eldest) { * return size() > MAX_ENTRIES; * } * </pre> * * <p>This method typically does not modify the map in any way, * instead allowing the map to modify itself as directed by its * return value. It <i>is</i> permitted for this method to modify * the map directly, but if it does so, it <i>must</i> return * <tt>false</tt> (indicating that the map should not attempt any * further modification). The effects of returning <tt>true</tt> * after modifying the map from within this method are unspecified. * * <p>This implementation merely returns <tt>false</tt> (so that this * map acts like a normal map - the eldest element is never removed). * * @param eldest The least recently inserted entry in the map, or if * this is an access-ordered map, the least recently accessed * entry. This is the entry that will be removed it this * method returns <tt>true</tt>. If the map was empty prior * to the <tt>put</tt> or <tt>putAll</tt> invocation resulting * in this invocation, this will be the entry that was just * inserted; in other words, if the map contains a single * entry, the eldest entry is also the newest. * @return <tt>true</tt> if the eldest entry should be removed * from the map; <tt>false</tt> if it should be retained. */ protected boolean removeEldestEntry(Map.Entry<K,V> eldest) { return false; }
private static final int MAX_ENTRIES = 100; protected boolean removeEldestEntry(Map.Entry eldest) { return size() > MAX_ENTRIES; }
afterNodeAccess(Node<K,V> e)方法
首先来看一下afterNodeAccess方法被调用的时机:
- LinkedHashMap中调用
public V get(Object key)
方法时,且accessOrder=true - LinkedHashMap中调用
public V getOrDefault(Object key, V defaultValue)
方法时,且accessOrder=true - HashMap中调用
put
方法添加一个Key已经存在的元素 - HashMap中调用
public boolean replace(K key, V oldValue, V newValue)
方法时 - HashMap中调用
public V replace(K key, V value)
方法时 - HashMap中调用
public V computeIfAbsent(K key, Function<? super K, ? extends V> mappingFunction)
方法时,对应Key的值存且在不为null - HashMap中调用
public V computeIfPresent(K key, BiFunction<? super K, ? super V, ? extends V> remappingFunction)
方法时 - HashMap中调用
public V compute(K key, BiFunction<? super K, ? super V, ? extends V> remappingFunction)
方法时 - HashMap中调用
public V merge(K key, V value, BiFunction<? super V, ? super V, ? extends V> remappingFunction)
方法时
该方法的主要作用是在accessOrder=true的情况下,将e节点转移至双向队列末尾。
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;
}
}
afterNodeRemoval(Node<K,V> e)方法
该方法的作用是在元素被移除后将列表中的元素也进行移除。
void afterNodeRemoval(Node<K,V> e) { // unlink
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;
}
总结
LinkedHashMap继承了HashMap,通过Entry
对象构建了一个双向队列,并通过重写HashMap中预留的空的钩子方法维护元素的顺序。当accessOrder=false,默认根据元素的插入顺序排序;accessOrder=true,根据元素的访问顺序进行排序。
根据LinkedHashMap的特点,能够很方便的实现一个LRU缓存算法,如下:
public class LinkedHashMapLRUCache extends LinkedHashMap {
private Integer CACHE_MAX_COUNT;
public LinkedHashMapLRUCache(int initialCapacity) {
super(initialCapacity, 0.75f, true);
CACHE_MAX_COUNT = initialCapacity;
}
@Override
protected boolean removeEldestEntry(Map.Entry eldest) {
return size() > CACHE_MAX_COUNT;
}
}
本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 逐光の博客!
评论