JDK源碼分析(6)之 LinkedHashMap 相關

LinkedHashMap實質是HashMap+LinkedList,提供了順序訪問的功能;因此在看這篇博客以前最好先看一下我以前的兩篇博客,HashMap 相關LinkedList 相關html

1、總體結構

1. 定義

public class LinkedHashMap<K,V> extends HashMap<K,V> implements Map<K,V> {}

<img src="https://img2018.cnblogs.com/blog/1119937/201901/1119937-20190121094619602-2085192613.png" width = "350" alt="LinkedHashMap 結構" align=center />java

從上述定義中也能看到LinkedHashMap其實就是繼承了HashMap,並加了雙向鏈表記錄順序,代碼和結構自己不難,可是其中結構的組織,代碼複用這些地方十分值得咱們學習;具體結構如圖所示:node

<img src="https://img2018.cnblogs.com/blog/1119937/201901/1119937-20190121094715988-607190851.png" width = "600" alt="LinkedHashMap 結構" align=center />app

2. 構造函數和成員變量

public LinkedHashMap(int initialCapacity, float loadFactor) {}
public LinkedHashMap(int initialCapacity) {}
public LinkedHashMap() {}
public LinkedHashMap(Map<? extends K, ? extends V> m) {}
public LinkedHashMap(int initialCapacity, float loadFactor, boolean accessOrder) {}

/**
 * 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的5個構造函數和HashMap的做用基本是同樣的,都是初始化initialCapacityloadFactor,可是多了一個accessOrder,這也是LinkedHashMap最重要的一個成員變量了;ide

  • accessOrdertrue的時候,表示LinkedHashMap中記錄的是訪問順序,也是就沒放get一個元素的時候,這個元素就會被移到鏈表的尾部;
  • accessOrderfalse的時候,表示LinkedHashMap中記錄的是插入順序;

3. Entry關係

<img src="https://img2018.cnblogs.com/blog/1119937/201901/1119937-20190121094800076-1747634277.png" width = "800" alt="hashmap_entry" align=center />函數

扎眼一看可能會以爲HashMap體系的節點繼承關係比較混亂;一因此這樣設計由於源碼分析

  • LinkedHashMap繼承至HashMap,其中的節點一樣有普通節點和樹節點兩種;而且樹節點不多使用;
  • 如今的設計中,樹節點是能夠徹底複用的,可是HashMap的樹節點,會浪費雙向鏈表的能力;
  • 若是不這樣設計,則至少須要兩條繼承關係,而且須要抽出雙向鏈表的能力,整個繼承體系以及方法的複用會變得很是複雜,不利於擴展;

2、重要方法

上面咱們已經講了LinkedHashMap就是HashMap+鏈表,因此咱們只須要在結構有可能改變的地方加上鍊表的修改就能夠了,結構可能改變的地方只要有put/get/replace,這裏須要注意擴容的時候雖然結構改變了,可是節點的順序仍然保持不變,因此擴容能夠徹底複用;學習

1. put 方法

  • 未找到key時,直接在最後添加一個節點
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);
  linkNodeLast(p);
  return p;
}

TreeNode<K,V> newTreeNode(int hash, K key, V value, Node<K,V> next) {
  TreeNode<K,V> p = new TreeNode<K,V>(hash, key, value, next);
  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;
  }
}

上面代碼很簡單,可是很清晰的將添加節點到最後的邏輯抽離的出來;ui

  • 找到key,則替換value,這部分須要聯繫 HashMap 相關 中的put方法部分;
// HashMap.putVal
...
// 若是找到key
if (e != null) { // existing mapping for key
  V oldValue = e.value;
  if (!onlyIfAbsent || oldValue == null)
    e.value = value;
  afterNodeAccess(e);
  return oldValue;
}

// 若是沒有找到key
++modCount;
if (++size > threshold)
  resize();
afterNodeInsertion(evict);
return null;
...

在以前的HashMap源碼分析當中能夠看到有幾個空的方法this

void afterNodeAccess(Node<K,V> p) { }
void afterNodeInsertion(boolean evict) { }
void afterNodeRemoval(Node<K,V> p) { }

這三個就是用來調整鏈表位置的事件方法,能夠看到HashMap.putVal中就使用了兩個,

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;
  }
}

afterNodeAccess能夠算是LinkedHashMap比較核心的方法了,當訪問了一個節點的時候,若是accessOrder = true則將節點放到最後,若是accessOrder = false則不變;

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);
  }
}

protected boolean removeEldestEntry(Map.Entry<K,V> eldest) {
  return false;
}

afterNodeInsertion方法是插入節點後是否須要移除最老的節點,這個方法和維護鏈表無關,可是對於LinkedHashMap的用途有很大做用,後天會舉例說明;

2. get 方法

public V get(Object key) {
  Node<K,V> e;
  if ((e = getNode(hash(key), key)) == null)
    return null;
  if (accessOrder)
    afterNodeAccess(e);
  return e.value;
}

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;
}

get方法主要也是經過afterNodeAccess來維護鏈表位置關係; 以上就是LinkedHashMap鏈表位置關係調整的主要方法了;

3. containsValue 方法

public boolean containsValue(Object value) {
  for (LinkedHashMap.Entry<K,V> e = head; e != null; e = e.after) {
    V v = e.value;
    if (v == value || (value != null && value.equals(v)))
      return true;
  }
  return false;
}

能夠看到LinkedHashMap還重寫了containsValue,在HashMap中尋找value的時候,須要遍歷全部節點,他是遍歷每一個哈希桶,在依次遍歷桶中的鏈表;而在LinkedHashMap裏面要遍歷全部節點的時候,就能夠直接經過雙向鏈表進行遍歷了;

3、應用

public class Cache<K, V> {
  private static final float DEFAULT_LOAD_FACTOR = 0.75f;
  private final int MAX_CAPACITY;
  private LinkedHashMap<K, V> map;

  public Cache(int capacity, boolean accessOrder) {
    capacity = (int) Math.ceil((MAX_CAPACITY = capacity) / DEFAULT_LOAD_FACTOR) + 1;
    map = new LinkedHashMap(capacity, DEFAULT_LOAD_FACTOR, accessOrder) {
      @Override
      protected boolean removeEldestEntry(Map.Entry eldest) {
        return size() > MAX_CAPACITY;
      }
    };
  }

  public synchronized void put(K key, V value) {
    map.put(key, value);
  }

  public synchronized V get(K key) {
    return map.get(key);
  }

  @Override
  public String toString() {
    StringBuilder sb = new StringBuilder();
    for (Map.Entry entry : map.entrySet()) {
      sb.append(String.format("%s:%s ", entry.getKey(), entry.getValue()));
    }
    return sb.toString();
  }
}

以上是就是一個LinkedHashMap的簡單應用,

  • accessOrder = true時,就是LRUCache,
  • accessOrder = false時,就是FIFOCache;
// LRUCache
Cache<String, String> cache = new Cache<>(3, true);
cache.put("a", "1");
cache.put("b", "2");
cache.put("c", "3");
cache.put("d", "4");
cache.get("c");

System.out.println(cache);

// 打印:b:2 d:4 c:3

// FIFOCache
Cache<String, String> cache = new Cache<>(3, false);
cache.put("a", "1");
cache.put("b", "2");
cache.put("c", "3");
cache.put("d", "4");
cache.get("c");

System.out.println(cache);

// 打印:b:2 c:3 d:4

總結

  • 整體而言LinkedHashMap的代碼比較簡單,可是我以爲裏面代碼的組織,邏輯的提取等方面特別值得借鑑;
相關文章
相關標籤/搜索