天天看點

JDK8 HashMap 源碼解析

HashMap中資料結構

在jdk1.7中,HashMap采用數組+連結清單(拉鍊法)。因為數組是一組連續的記憶體空間,易查詢,不易增删,而連結清單是不連續的記憶體空間,通過節點互相連接配接,易删除,不易查詢。HashMap結合這兩者的優秀之處來提高效率。

而在jdk1.8時,為了解決當hash碰撞過于頻繁,而連結清單的查詢效率(時間複雜度為O(n))過低時,當連結清單的長度達到一定值(預設是8)時,将連結清單轉換成紅黑樹(時間複雜度為O(lg n)),極大的提高了查詢效率。

如圖所示:

JDK8 HashMap 源碼解析

HashMap初始化

以下代碼未經特别聲明,都是jdk1.8。

/**
 * The default initial capacity - MUST be a power of two.
 */
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16

 /**
 * Constructs an empty <tt>HashMap</tt> with the default initial capacity
 * (16) and the default load factor (0.75).
 */
public HashMap() {
    this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted
}
           

HashMap的預設大小是16。檢視

HashMap

的構造方法,發現沒有執行new操作,猜測可能跟

ArrayList

一樣是在第一次

add

的時候開辟的記憶體,于是檢視

put

方法。

put方法

關于Node節點

HashMap将hash,key,value,next已經封裝到一個靜态内部類Node上。它實作了

Map.Entry<K,V>

接口。

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

然後在定義一個Node數組table

transient Node<K,V>[] table;
           

hash實作

當我們put的時候,首先計算

key

hash

值,這裡調用了

hash

方法,

hash

方法實際是讓

key.hashCode()

key.hashCode()>>>16

進行異或操作,高16bit補0,一個數和0異或不變,是以 hash 函數大概的作用就是:高16bit不變,低16bit和高16bit做了一個異或,目的是減少碰撞。按照函數注釋,因為bucket數組大小是2的幂,計算下标

index = (table.length - 1) & hash

,如果不做 hash 處理,相當于散列生效的隻有幾個低 bit 位,為了減少散列的碰撞,設計者綜合考慮了速度、作用、品質之後,使用高16bit和低16bit異或來簡單處理減少碰撞,而且JDK8中用了複雜度 O(logn)的樹結構來提升碰撞下的性能。

public V put(K key, V value) {
    return putVal(hash(key), key, value, false, true);
}
static final int hash(Object key) {
    int h;
    return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
           

實作方法

  • 如果目前數組table為null,進行resize()初始化
  • 否則計算數組索引

    i = (n - 1) & hash

  • 如果這個table[i]值為空,那麼就将這個Node鍵值對放在這裡
  • 判斷key是否與table[i]重複,重複則替換
  • 不重複在判斷table[i]是否連接配接了一個連結清單,連結清單為空則new 一個Node鍵值對,連結清單不為空就循環直到最後一個節點的next為null或者出現出現重複key值
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;
    //如果table[i]為空,那就把這個鍵值對放在table[i], i = (n - 1) & hash 相等于 hash % n,
    //但是hash後按位與 n-1,比%模運算取餘要快
    if ((p = tab[i = (n - 1) & hash]) == null)
        tab[i] = newNode(hash, key, value, null);
    //當另一個key的hash值已經存在時
    else {
        Node<K,V> e; K k;
        // table[i].key == key
        if (p.hash == hash &&
            ((k = p.key) == key || (key != null && key.equals(k))))
            e = p;
            //JDK8在哈希碰撞的連結清單長度達到TREEIFY_THRESHOLD(預設8)後,
            //會把該連結清單轉變成樹結構,提高了性能。
        else if (p instanceof TreeNode)
            e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
        else {
          //周遊table[i]所對應的連結清單,直到最後一個節點的next為null或者有重複的key值
            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;
            }
        }
        //key重複,替換value
        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;
}

// Callbacks to allow LinkedHashMap post-actions
void afterNodeAccess(Node<K,V> p) { }
void afterNodeInsertion(boolean evict) { }
void afterNodeRemoval(Node<K,V> p) { }
           

get方法

首先通過

hash

函數找到索引,然後判斷map為null,再判斷table[i]是否等于key,然後在找與table相連的連結清單的key是否相等。

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

jdk1.7中的線程安全問題(resize死循環)

當HashMap的size超過Capacity*loadFactor時,需要對HashMap進行擴容。具體方法是,建立一個新的,長度為原來Capacity兩倍的數組,保證新的Capacity仍為2的N次方,進而保證上述尋址方式仍适用。同時需要通過如下transfer方法将原來的所有資料全部重新插入(rehash)到新的數組中。

下列代碼基于 jdk1.7.0_79

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

該方法并不保證線程安全,而且在多線程并發調用時,可能出現死循環。其執行過程如下。從步驟2可見,轉移時連結清單順序反轉。

  1. 周遊原數組中的元素
  2. 對連結清單上的每一個節點周遊:用next取得要轉移那個元素的下一個,将e轉移到新數組的頭部,使用頭插法插入節點
  3. 循環2,直到連結清單節點全部轉移
  4. 循環1,直到所有元素全部轉移

單線程rehash

單線程情況下,rehash無問題。下圖示範了單線程條件下的rehash過程

JDK8 HashMap 源碼解析

多線程并發下的rehash

這裡假設有兩個線程同時執行了put操作并引發了rehash,執行了transfer方法,并假設線程一進入transfer方法并執行完next = e.next後,因為線程排程所配置設定時間片用完而“暫停”,此時線程二完成了transfer方法的執行。此時狀态如下。

JDK8 HashMap 源碼解析

接着線程1被喚醒,繼續執行第一輪循環的剩餘部分

e.next = newTable[1] = null
newTable[1] = e = key(5)
e = next = key(9)
           

結果如下圖所示

JDK8 HashMap 源碼解析

接着執行下一輪循環,結果狀态圖如下所示

JDK8 HashMap 源碼解析

此時循環連結清單形成,并且key(11)無法加入到線程1的新數組。在下一次通路該連結清單時會出現死循環。

jdk1.8中的擴容

在jdk1.8中采用resize方法來對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;
        }
        // 沒超過最大值,就擴充為原來的2倍
        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);
    }
     // 計算新的resize上限
    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) {
      // 把每個bucket都移動到新的buckets中
        for (int j = 0; j < oldCap; ++j) {
            Node<K,V> e;
            if ((e = oldTab[j]) != null) {
              // 清除原來table[i]中的值
                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 { // 帶有連結清單時優化重hash
                    Node<K,V> loHead = null, loTail = null;
                    Node<K,V> hiHead = null, hiTail = null;
                    Node<K,V> next;
                    do {
                        next = e.next;
                        // 原索引,(e.hash & oldCap) == 0 說明 在put操作通過 hash & newThr
                        //計算出的索引值等于現在的索引值。
                        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);
                    // 原索引放到bucket裡
                    if (loTail != null) {
                        loTail.next = null;
                        newTab[j] = loHead;
                    }
                    // 原索引+oldCap放到bucket裡
                    if (hiTail != null) {
                        hiTail.next = null;
                        newTab[j + oldCap] = hiHead;
                    }
                }
            }
        }
    }
    return newTab;
}
           

聲明兩對指針,維護兩個連結清單,依次在末端添加新的元素,在多線程操作的情況下,無非是第二個線程重複第一個線程一模一樣的操作。

是以不會産生jdk1.7擴容時的resize死循環問題。

jdk1.8中hashmap的确不會因為多線程put導緻死循環,但是依然有其他的弊端。是以多線程情況下還是建議使用concurrenthashmap。

面試問題

  1. 如果new HashMap(19),bucket數組多大?

    HashMap的bucket 數組大小一定是2的幂,如果new的時候指定了容量且不是2的幂,實際容量會是最接近(大于)指定容量的2的幂,比如 new HashMap<>(19),比19大且最接近的2的幂是32,實際容量就是32。

    基礎知識

    JDK8 HashMap 源碼解析

    簡便方法:

    如對

    a

    按位取反,則得到的結果為

    -(a+1)

    此條運算方式對正數負數和零都适用。

    源碼

    /**
     * Returns a power of two size for the given target capacity.
     */
    static final int tableSizeFor(int cap) {
        int n = cap - 1;
        n |= n >>> 1;
        n |= n >>> 2;
        n |= n >>> 4;
        n |= n >>> 8;
        n |= n >>> 16;
        return (n < 0) ? 1 : (n >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1;
    }
               

    解析

    先來分析有關n位操作部分:先來假設n的二進制為01xxx...xxx。接着

    對n右移1位:001xx...xxx,再位或:011xx...xxx

    對n右移2為:00011...xxx,再位或:01111...xxx

    此時前面已經有四個1了,再右移4位且位或可得8個1

    同理,有8個1,右移8位肯定會讓後八位也為1。

    綜上可得,該算法讓最高位的1後面的位全變為1。

    最後再讓結果n+1,即得到了2的整數次幂的值了。

    現在回來看看第一條語句:

    int n = cap - 1;

      讓cap-1再指派給n的目的是另找到的目标值大于或等于原值。例如二進制1000,十進制數值為8。如果不對它減1而直接操作,将得到答案10000,即16。顯然不是結果。減1後二進制為111,再進行操作則會得到原來的數值1000,即8。

      這種方法的效率非常高,可見Java8對容器優化了很多,很強哈。其他之後再進行分析吧。

  2. HashMap什麼時候開辟bucket數組占用記憶體?

    HashMap在new 後并不會立即配置設定bucket數組,而是第一次put時初始化,類似ArrayList在第一次add時配置設定空間。

  3. HashMap何時擴容?

    HashMap 在 put 的元素數量大于 Capacity * LoadFactor(預設16 * 0.75) 之後會進行擴容。

  4. 當兩個對象的hashcode相同會發生什麼?

    碰撞

  5. 如果兩個鍵的hashcode相同,你如何擷取值對象?

    周遊與hashCode值相等時相連的連結清單,直到相等或者null

  6. 你了解重新調整HashMap大小存在什麼問題嗎?

參考文檔

  1. HashMap實作原理分析
  2. 由阿裡巴巴Java開發規約HashMap條目引發的故事
  3. Java8 HashMap之tableSizeFor
  4. Java 8系列之重新認識HashMap
  5. Java進階(六)從ConcurrentHashMap的演進看Java多線程核心技術