Java 源碼剖析(02)--HashMap 底層實現原理是什麼?

1)HashMap 底層實現

在 JDK 1.7 中 HashMap 是以數組加鏈表的形式組成的,JDK 1.8 之後新增了紅黑樹的組成結構,當鏈表大於 8 並且哈希桶的容量大於 64 時,鏈表結構會轉換成紅黑樹結構,它的組成結構如下圖所示:
在這裏插入圖片描述
數組中的元素我們稱之爲哈希桶,它的定義如下:

static class Node<K,V> implements Map.Entry<K,V> {
    final int hash;
    final K key;
    V value;
    Node<K,V> next;

    Node(int hash, K key, V value, Node<K,V> next) {
        this.hash = hash;
        this.key = key;
        this.value = value;
        this.next = next;
    }

    public final K getKey()        { return key; }
    public final V getValue()      { return value; }
    public final String toString() { return key + "=" + value; }

    public final int hashCode() {
        return Objects.hashCode(key) ^ Objects.hashCode(value);
    }

    public final V setValue(V newValue) {
        V oldValue = value;
        value = newValue;
        return oldValue;
    }

    public final boolean equals(Object o) {
        if (o == this)
            return true;
        if (o instanceof Map.Entry) {
            Map.Entry<?,?> e = (Map.Entry<?,?>)o;
            if (Objects.equals(key, e.getKey()) &&
                Objects.equals(value, e.getValue()))
                return true;
        }
        return false;
    }
}

可以看出每個哈希桶中包含了四個字段:hash、key、value、next,其中 next 表示鏈表的下一個節點。
JDK 1.8 之所以添加紅黑樹是因爲一旦鏈表過長,會嚴重影響 HashMap 的性能,而紅黑樹具有快速增刪改查的特點,這樣就可以有效的解決鏈表過長時操作比較慢的問題

2)知識擴展

2.1)HashMap 源碼分析

【以目前主流的 JDK 版本 1.8 爲例來進行源碼分析】
HashMap 源碼中包含了以下幾個屬性:

// HashMap 初始化長度
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16

// HashMap 最大長度
static final int MAXIMUM_CAPACITY = 1 << 30; // 1073741824

// 默認的加載因子 (擴容因子)
static final float DEFAULT_LOAD_FACTOR = 0.75f;

// 當鏈表長度大於此值且容量大於 64 時
static final int TREEIFY_THRESHOLD = 8;

// 轉換鏈表的臨界值,當元素小於此值時,會將紅黑樹結構轉換成鏈表結構
static final int UNTREEIFY_THRESHOLD = 6;

// 最小樹容量
static final int MIN_TREEIFY_CAPACITY =

2.2)什麼是加載因子?

加載因子也叫擴容因子或負載因子,用來判斷什麼時候進行擴容的,假如加載因子是 0.5,HashMap 的初始化容量是 16,那麼當 HashMap 中有 16*0.5=8 個元素時,HashMap 就會進行擴容。

加載因子爲什麼是 0.75 而不是 0.5 或者 1.0 呢?
這其實是出於容量和性能之間平衡的結果:

  • 當加載因子設置比較大的時候,擴容的門檻就被提高了,擴容發生的頻率比較低,佔用的空間會比較小,但此時發生 Hash 衝突的機率就會提升,因此需要更復雜的數據結構來存儲元素,這樣對元素的操作時間就會增加,運行效率也會因此降低;
  • 而當加載因子值比較小的時候,擴容的門檻會比較低,因此會佔用更多的空間,此時元素的存儲就比較稀疏,發生哈希衝突的可能性就比較小,因此操作性能會比較高;
  • 爲了提升擴容效率,HashMap的容量(capacity)有一個固定的要求,那就是一定是2的冪【可以用位運算實現取模運算,位運算採用內存操作,且能解決負數問題】;所以,如果負載因子是3/4的話,那麼和capacity的乘積結果就可以是一個整數。

所以綜合了以上情況就取了一個 0.5 到 1.0 的平均數 0.75 作爲加載因子。

HashMap 源碼中三個重要方法:查詢、新增和數據擴容
查詢方法,源碼如下:

public V get(Object key) {
    Node<K,V> e;
    // 對 key 進行哈希操作
    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) {
        // 判斷第一個元素是否是要查詢的元素
        if (first.hash == hash && // always check first node
            ((k = first.key) == key || (key != null && key.equals(k))))
            return first;
        // 下一個節點非空判斷
        if ((e = first.next) != null) {
            // 如果第一節點是樹結構,則使用 getTreeNode 直接獲取相應的數據
            if (first instanceof TreeNode)
                return ((TreeNode<K,V>)first).getTreeNode(hash, key);
            do { // 非樹結構,循環節點判斷
                // hash 相等並且 key 相同,則返回此節點
                if (e.hash == hash &&
                    ((k = e.key) == key || (key != null && key.equals(k))))
                    return e;
            } while ((e = e.next) != null);
        }
    }
    return null;
}

從以上源碼可以看出,當哈希衝突時我們需要通過判斷 key 值是否相等,才能確認此元素是不是我們想要的元素。
新增方法,源碼如下:

public V put(K key, V value) {
    // 對 key 進行哈希操作
    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;
    // 根據 key 的哈希值計算出要插入的數組索引 i
    if ((p = tab[i = (n - 1) & hash]) == null)
        // 如果 table[i] 等於 null,則直接插入
        tab[i] = newNode(hash, key, value, null);
    else {
        Node<K,V> e; K k;
        // 如果 key 已經存在了,直接覆蓋 value
        if (p.hash == hash &&
            ((k = p.key) == key || (key != null && key.equals(k))))
            e = p;
        // 如果 key 不存在,判斷是否爲紅黑樹
        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;
                }
                //  key 已經存在直接覆蓋 value
                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;
}

新增方法的執行流程,如下圖所示:
在這裏插入圖片描述
擴容方法,源碼如下:

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;
        }
        // 擴大容量爲當前容量的兩倍,但不能超過 MAXIMUM_CAPACITY
        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
        // 如果初始化的值爲 0,則使用默認的初始化容量
        newCap = DEFAULT_INITIAL_CAPACITY;
        newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
    }
    // 如果新的容量等於 0
    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
    table = newTab;
    // 原數據不爲空,將原數據複製到新 table 中
    if (oldTab != null) {
        // 根據容量循環數組,複製非空元素到新 table
        for (int j = 0; j < oldCap; ++j) {
            Node<K,V> e;
            if ((e = oldTab[j]) != null) {
                oldTab[j] = null;
                // 如果鏈表只有一個,則進行直接賦值
                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
                    // 鏈表複製,JDK 1.8 擴容優化部分
                    Node<K,V> loHead = null, loTail = null;
                    Node<K,V> hiHead = null, hiTail = null;
                    Node<K,V> next;
                    do {
                        next = e.next;
                        // 原索引
                        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);
                    // 將原索引放到哈希桶中
                    if (loTail != null) {
                        loTail.next = null;
                        newTab[j] = loHead;
                    }
                    // 將原索引 + oldCap 放到哈希桶中
                    if (hiTail != null) {
                        hiTail.next = null;
                        newTab[j + oldCap] = hiHead;
                    }
                }
            }
        }
    }
    return newTab;
}

從以上源碼可以看出,JDK 1.8 在擴容時並沒有像 JDK 1.7 那樣,重新計算每個元素的哈希值,而是通過高位運算(e.hash & oldCap)來確定元素是否需要移動,比如 key1 的信息如下:

key1.hash = 10 0000 1010
oldCap = 16 0001 0000

使用 e.hash & oldCap 得到的結果,高一位爲 0,當結果爲 0 時表示元素在擴容時位置不會發生任何變化,而 key 2 信息如下:

key2.hash = 10 0001 0001
oldCap = 16 0001 0000

這時候得到的結果,高一位爲 1,當結果爲 1 時,表示元素在擴容時位置發生了變化,新的下標位置等於原下標位置 + 原數組長度,如下圖所示:【紅色的虛線圖代表了擴容時元素移動的位置】
在這裏插入圖片描述

2.2)HashMap 死循環分析

以 JDK 1.7 爲例,假設 HashMap 默認大小爲 2,原本 HashMap 中有一個元素 key(5),我們再使用兩個線程:t1 添加元素 key(3),t2 添加元素 key(7),當元素 key(3) 和 key(7) 都添加到 HashMap 中之後,線程 t1 在執行到 Entry<K,V> next = e.next; 時,交出了 CPU 的使用權,源碼如下:

void transfer(Entry[] newTable, boolean rehash) {
    int newCapacity = newTable.length;
    for (Entry<K,V> e : table) {
        while(null != e) {
            Entry<K,V> next = e.next; // 線程一執行此處
            if (rehash) {
                e.hash = null == e.key ? 0 : hash(e.key);
            }
            int i = indexFor(e.hash, newCapacity);
            e.next = newTable[i];
            newTable[i] = e;
            e = next;
        }
    }
}

那麼此時線程 t1 中的 e 指向了 key(3),而 next 指向了 key(7) ;之後線程 t2 重新 rehash 之後鏈表的順序被反轉,鏈表的位置變成了 key(5) → key(7) → key(3),其中 “→” 用來表示下一個元素。

當 t1 重新獲得執行權之後,先執行 newTalbe[i] = e 把 key(3) 的 next 設置爲 key(7),而下次循環時查詢到 key(7) 的 next 元素爲 key(3),於是就形成了 key(3) 和 key(7) 的循環引用,因此就導致了死循環的發生,如下圖所示:
在這裏插入圖片描述
發生死循環的原因是 JDK 1.7 鏈表插入方式爲首部倒序插入,這個問題在 JDK 1.8 得到了改善,變成了尾部正序插入。

3)總結

本文介紹了 HashMap 的底層數據結構,在 JDK 1.7 時 HashMap 是由數組和鏈表組成的,而 JDK 1.8 則新增了紅黑樹結構,當鏈表的長度大於 8 並且容量大於 64 時會轉換爲紅黑樹存儲,以提升元素的操作性能。同時還介紹了 HashMap 的三個重要方法,查詢、添加和擴容,以及 JDK 1.7 resize() 在併發環境下導致死循環的原因。
【補充】

  • HashMap採用鏈地址法,低十六位和高十六位異或以及hash&length-1來減少hash衝突;
  • 在1.7採用頭插入,1.8優化爲尾插入,因爲頭插入容易產生環形鏈表死循環問題;
  • 在1.7擴容位置爲hash &新容量-1,1.8是如果只有首節點那麼跟1.7一樣,否則判斷是否爲紅黑樹或者鏈表,再通過hash&原容量判斷,爲0放低位,否則高位,低位位置不變,高位位置=原位置+原容量;
  • 樹化和退樹化8和6的選擇,紅黑樹平均查找爲logn,長度爲8時,查找長度爲3,而鏈表平均爲8除以2;當爲6時,查找長度一樣,而樹化需要時間;然後中間就一個數防止頻繁轉換;
  • 容量設置爲2的n次方主要是可以用位運算實現取模運算,位運算採用內存操作,且能解決負數問題;同時hash&length-1時,length-1爲奇數的二進制都爲1,index的結果就等同與hashcode後幾位,只要hashcode均勻,那麼hash碰撞就少;
  • 負載因子.75主要是太大容易造成hash衝突,太小浪費空間。
    ——————————————————————————————————————————————
    關注公衆號,回覆 【算法】,獲取高清算法書!
    在這裏插入圖片描述
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章