1. 前言
上一篇從源碼方面了解了JDK1.7中Hashmap的實現原理,可以看到其源碼相對還是比較簡單的。本篇筆者和大家一起學習下JDK1.8下Hashmap的實現。JDK1.8中對Hashmap做了以下改動。
- 默認初始化容量=0
- 引入紅黑樹,優化數據結構
- 將鏈表頭插法改為尾插法,解決1.7中多線程循環鏈表的bug
- 優化hash算法
- resize計算索引位置的算法改進
- 先插入后擴容
2. Hashmap中put()過程
筆者的源碼是OpenJDK1.8的源碼。
JDK1.8中,Hashmap將基本元素由Entry換成了Node,不過查看源碼后發現換湯不換葯,這里沒啥好說的。
下圖是一位大神級別畫的圖,自己就不再造輪子了。客官請看
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;
// 判斷數組是否為空,長度是否為0,是則進行擴容數組初始化
if ((tab = table) == null || (n = tab.length) == 0)
n = (tab = resize()).length;
// 通過hash算法找到數組下標得到數組元素,為空則新建
if ((p = tab[i = (n - 1) & hash]) == null)
tab[i] = newNode(hash, key, value, null);
else {
Node<K,V> e; K k;
// 找到數組元素,hash相等同時key相等,則直接覆蓋
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
e = p;
// 該數組元素在鏈表長度>8后形成紅黑樹結構的對象,p為樹結構已存在的對象
else if (p instanceof TreeNode)
e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
else {
// 該數組元素hash相等,key不等,同時鏈表長度<8.進行遍歷尋找元素,有就覆蓋無則新建
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
// 鏈表長度>=8 結構轉為 紅黑樹
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;
// onlyIfAbsent默認false
if (!onlyIfAbsent || oldValue == null)
e.value = value;
afterNodeAccess(e);
return oldValue;
}
}
++modCount;
// 判斷是否需要擴容
if (++size > threshold)
resize();
afterNodeInsertion(evict);
return null;
}
基本過程如下:
-
檢查數組是否為空,執行resize()擴充;在實例化HashMap時,並不會進行初始化數組)
-
通過hash值計算數組索引,獲取該索引位的首節點。
-
如果首節點為null(沒發生碰撞),則創建新的數組元素,直接添加節點到該索引位(bucket)。
-
如果首節點不為null(發生碰撞),那么有3種情況
① key和首節點的key相同,覆蓋old value(保證key的唯一性);否則執行②或③
② 如果首節點是紅黑樹節點(TreeNode),將鍵值對添加到紅黑樹。
③ 如果首節點是鏈表,進行遍歷尋找元素,有就覆蓋無則新建,將鍵值對添加到鏈表。添加之后會判斷鏈表長度是否到達TREEIFY_THRESHOLD - 1這個閾值,“嘗試”將鏈表轉換成紅黑樹。
-
最后判斷當前元素個數是否大於threshold,擴充數組。
3. Hashmap中get()過程
public V get(Object key) {
Node<K,V> e;
return (e = getNode(hash(key), key)) == null ? null : e.value;
}
final Node<K,V> getNode(int hash, Object key) {
Node<K,V>[] tab; Node<K,V> first, e; int n; K k;
if ((tab = table) != null && (n = tab.length) > 0 &&
(first = tab[(n - 1) & hash]) != null) {
// 永遠檢查第一個node
if (first.hash == hash && // always check first node
((k = first.key) == key || (key != null && key.equals(k))))
return first;
if ((e = first.next) != null) {
if (first instanceof TreeNode) // 樹查找
return ((TreeNode<K,V>)first).getTreeNode(hash, key);
do {
if (e.hash == hash && // 遍歷鏈表
((k = e.key) == key || (key != null && key.equals(k))))
return e;
} while ((e = e.next) != null);
}
}
return null;
}
在Hashmap1.8中,無論是存元素還是取元素,都是優先判斷bucket上第一個元素是否匹配,而在1.7中則是直接遍歷查找。
基本過程如下:
- 根據key計算hash;
- 檢查數組是否為空,為空返回null;
- 根據hash計算bucket位置,如果bucket第一個元素是目標元素,直接返回。否則執行4;
- 如果bucket上元素大於1並且是樹結構,則執行樹查找。否則執行5;
- 如果是鏈表結構,則遍歷尋找目標
4. Hashmap中resize()過程
final Node<K,V>[] resize() {
Node<K,V>[] oldTab = table;
int oldCap = (oldTab == null) ? 0 : oldTab.length;
int oldThr = threshold;
int newCap, newThr = 0;
if (oldCap > 0) {
// 如果已達到最大容量不在擴容
if (oldCap >= MAXIMUM_CAPACITY) {
threshold = Integer.MAX_VALUE;
return oldTab;
}
// 通過位運算擴容到原來的兩倍
else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
oldCap >= DEFAULT_INITIAL_CAPACITY)
newThr = oldThr << 1; // double threshold
}
else if (oldThr > 0) // initial capacity was placed in threshold
newCap = oldThr;
else { // zero initial threshold signifies using defaults
newCap = DEFAULT_INITIAL_CAPACITY;
newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
}
if (newThr == 0) {
float ft = (float)newCap * loadFactor;
newThr = (newCap < MAXIMUM_CAPACITY && ft < (float)MAXIMUM_CAPACITY ?
(int)ft : Integer.MAX_VALUE);
}
// 新的擴容臨界值
threshold = newThr;
@SuppressWarnings({"rawtypes","unchecked"})
Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap];
table = newTab;
if (oldTab != null) {
for (int j = 0; j < oldCap; ++j) {
Node<K,V> e;
if ((e = oldTab[j]) != null) {
oldTab[j] = null;
// 如果該位置元素沒有next節點,將該元素放入新數組
if (e.next == null)
newTab[e.hash & (newCap - 1)] = e;
else if (e instanceof TreeNode)
// 樹節點
((TreeNode<K,V>)e).split(this, newTab, j, oldCap);
else { // preserve order
// 鏈表節點。
// lo串的新索引位置與原先相同
Node<K,V> loHead = null, loTail = null;
// hi串的新索引位置為[原先位置j+oldCap]
Node<K,V> hiHead = null, hiTail = null;
Node<K,V> next;
do {
next = e.next;
// 原索引,oldCap是2的n次方,二進制表示只有一個1,其余是0
if ((e.hash & oldCap) == 0) {
if (loTail == null)
loHead = e;
else
// 尾插法
loTail.next = e;
loTail = e;
}
// 原索引+oldCap
else {
if (hiTail == null)
hiHead = e;
else
hiTail.next = e;
hiTail = e;
}
} while ((e = next) != null);
// 根據hash判斷該bucket上的整個鏈表的index還是舊數組的index,還是index+oldCap
if (loTail != null) {
loTail.next = null;
newTab[j] = loHead;
}
if (hiTail != null) {
hiTail.next = null;
newTab[j + oldCap] = hiHead;
}
}
}
}
}
return newTab;
}
JDK1.8版本中擴容相對復雜。在1.7版本中,重新根據hash計算索引位置即可;而在1.8版本中分2種情況,下邊用圖例來解釋。
5. 總結
其余還有為什么閾值=8轉紅黑樹,長度<=6 轉鏈表這些問題。基本都是數據科學家根據概率做出的經驗值,同時避免數據結構頻繁的轉換引起的性能開銷。
整體看來,JDK1.8主要在數據結構、算法和性能上對1.7進行了優化。
6. AD
歡迎大家關注公眾號【當我遇上你】, 每天第一時間與您分享干貨。