1. 程式人生 > >JDK原始碼分析(6)ConcurrentHashMap

JDK原始碼分析(6)ConcurrentHashMap

JDK版本

ConcurrentHashMap原始碼分析

  1. table:預設為null,初始化發生在第一次插入操作,預設大小為16的陣列,用來儲存Node節點資料,擴容時大小總是2的冪次方。
  2. nextTable:預設為null,擴容時新生成的陣列,其大小為原陣列的兩倍。
  • sizeCtl :預設為0,用來控制table的初始化和擴容操作,具體應用在後續會體現出來。
  • -1 代表table正在初始化
  • -N 表示有N-1個執行緒正在進行擴容操作
  • 其餘情況:
    1、如果table未初始化,表示table需要初始化的大小。
    2、如果table初始化完成,表示table的容量,預設是table大小的0.75倍,居然用這個公式算0.75(n - (n >>> 2))。
  • Node:儲存key,value及key的hash值的資料結構。
class Node<K,V> implements Map.Entry<K,V> {
    final int hash;
    final K key;
    volatile V val;
    volatile Node<K,V> next;
    ...
}

其中value和next都用volatile修飾,保證併發的可見性。

  • ForwardingNode:一個特殊的Node節點,hash值為-1,其中儲存nextTable的引用。
final class ForwardingNode<K,V> extends Node<K,V> {
    final Node<K,V>[] nextTable;
    ForwardingNode(Node<K,V>[] tab) {
        super(MOVED, null, null, null);
        this.nextTable = tab;
    }
}

只有table發生擴容的時候,ForwardingNode才會發揮作用,作為一個佔位符放在table中表示當前節點為null或則已經被移動。

例項初始化

例項化ConcurrentHashMap時帶引數時,會根據引數調整table的大小,假設引數為100,最終會調整成256,確保table的大小總是2的冪次方,演算法如下:

ConcurrentHashMap<String, String> hashMap = new ConcurrentHashMap<>(100);
private static final int tableSizeFor(int c) {
    int n = c - 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;
}

注意,ConcurrentHashMap在建構函式中只會初始化sizeCtl值,並不會直接初始化table,而是延緩到第一次put操作。

table初始化

前面已經提到過,table初始化操作會延緩到第一次put行為。但是put是可以併發執行的,Doug Lea是如何實現table只初始化一次的?讓我們來看看原始碼的實現。

private final Node<K,V>[] initTable() {
    Node<K,V>[] tab; int sc;
    while ((tab = table) == null || tab.length == 0) {
//如果一個執行緒發現sizeCtl<0,意味著另外的執行緒執行CAS操作成功,當前執行緒只需要讓出cpu時間片
        if ((sc = sizeCtl) < 0) 
            Thread.yield(); // lost initialization race; just spin
        else if (U.compareAndSwapInt(this, SIZECTL, sc, -1)) {
            try {
                if ((tab = table) == null || tab.length == 0) {
                    int n = (sc > 0) ? sc : DEFAULT_CAPACITY;
                    @SuppressWarnings("unchecked")
                    Node<K,V>[] nt = (Node<K,V>[])new Node<?,?>[n];
                    table = tab = nt;
                    sc = n - (n >>> 2);
                }
            } finally {
                sizeCtl = sc;
            }
            break;
        }
    }
    return tab;
}

sizeCtl預設為0,如果ConcurrentHashMap例項化時有傳引數,sizeCtl會是一個2的冪次方的值。所以執行第一次put操作的執行緒會執行Unsafe.compareAndSwapInt方法修改sizeCtl為-1,有且只有一個執行緒能夠修改成功,其它執行緒通過Thread.yield()讓出CPU時間片等待table初始化完成。

put操作

假設table已經初始化完成,put操作採用CAS+synchronized實現併發插入或更新操作,具體實現如下。

final V putVal(K key, V value, boolean onlyIfAbsent) {
    if (key == null || value == null) throw new NullPointerException();
    int hash = spread(key.hashCode());
    int binCount = 0;
    for (Node<K,V>[] tab = table;;) {
        Node<K,V> f; int n, i, fh;
        if (tab == null || (n = tab.length) == 0)
            tab = initTable();
        else if ((f = tabAt(tab, i = (n - 1) & hash)) == null) {
            if (casTabAt(tab, i, null, new Node<K,V>(hash, key, value, null)))
                break;                   // no lock when adding to empty bin
        }
        else if ((fh = f.hash) == MOVED)
            tab = helpTransfer(tab, f);
        ...省略部分程式碼
    }
    addCount(1L, binCount);
    return null;
}
  1. hash演算法
static final int spread(int h) {return (h ^ (h >>> 16)) & HASH_BITS;}
  1. table中定位索引位置,n是table的大小
int index = (n - 1) & hash
  1. 獲取table中對應索引的元素f。
    Doug Lea採用Unsafe.getObjectVolatile來獲取,也許有人質疑,直接table[index]不可以麼,為什麼要這麼複雜?
    在java記憶體模型中,我們已經知道每個執行緒都有一個工作記憶體,裡面儲存著table的副本,雖然table是volatile修飾的,但不能保證執行緒每次都拿到table中的最新元素,Unsafe.getObjectVolatile可以直接獲取指定記憶體的資料,保證了每次拿到資料都是最新的。
  2. 如果f為null,說明table中這個位置第一次插入元素,利用Unsafe.compareAndSwapObject方法插入Node節點。
  • 如果CAS成功,說明Node節點已經插入,隨後addCount(1L, binCount)方法會檢查當前容量是否需要進行擴容。
  • 如果CAS失敗,說明有其它執行緒提前插入了節點,自旋重新嘗試在這個位置插入節點。
  1. 如果f的hash值為-1,說明當前f是ForwardingNode節點,意味有其它執行緒正在擴容,則一起進行擴容操作。
  2. 其餘情況把新的Node節點按連結串列或紅黑樹的方式插入到合適的位置,這個過程採用同步內建鎖實現併發,程式碼如下:
synchronized (f) {
    if (tabAt(tab, i) == f) {
        if (fh >= 0) {
            binCount = 1;
            for (Node<K,V> e = f;; ++binCount) {
                K ek;
                if (e.hash == hash &&
                    ((ek = e.key) == key ||
                     (ek != null && key.equals(ek)))) {
                    oldVal = e.val;
                    if (!onlyIfAbsent)
                        e.val = value;
                    break;
                }
                Node<K,V> pred = e;
                if ((e = e.next) == null) {
                    pred.next = new Node<K,V>(hash, key,
                                              value, null);
                    break;
                }
            }
        }
        else if (f instanceof TreeBin) {
            Node<K,V> p;
            binCount = 2;
            if ((p = ((TreeBin<K,V>)f).putTreeVal(hash, key,
                                           value)) != null) {
                oldVal = p.val;
                if (!onlyIfAbsent)
                    p.val = value;
            }
        }
    }
}

在節點f上進行同步,節點插入之前,再次利用tabAt(tab, i) == f判斷,防止被其它執行緒修改。

  1. 如果f.hash >= 0,說明f是連結串列結構的頭結點,遍歷連結串列,如果找到對應的node節點,則修改value,否則在連結串列尾部加入節點。
  2. 如果f是TreeBin型別節點,說明f是紅黑樹根節點,則在樹結構上遍歷元素,更新或增加節點。
  3. 如果連結串列中節點數binCount >= TREEIFY_THRESHOLD(預設是8),則把連結串列轉化為紅黑樹結構。

table擴容

當table容量不足的時候,即table的元素數量達到容量閾值sizeCtl,需要對table進行擴容。
整個擴容分為兩部分:

  1. 構建一個nextTable,大小為table的兩倍。
  2. 把table的資料複製到nextTable中。

這兩個過程在單執行緒下實現很簡單,但是ConcurrentHashMap是支援併發插入的,擴容操作自然也會有併發的出現,這種情況下,第二步可以支援節點的併發複製,這樣效能自然提升不少,但實現的複雜度也上升了一個臺階。

先看第一步,構建nextTable,毫無疑問,這個過程只能只有單個執行緒進行nextTable的初始化,具體實現如下:

private final void addCount(long x, int check) {
    ...
    if (check >= 0) {
        Node<K,V>[] tab, nt; int n, sc;
        while (s >= (long)(sc = sizeCtl) && (tab = table) != null &&
               (n = tab.length) < MAXIMUM_CAPACITY) {
            int rs = resizeStamp(n);
            if (sc < 0) {
                if ((sc >>> RESIZE_STAMP_SHIFT) != rs || sc == rs + 1 ||
                    sc == rs + MAX_RESIZERS || (nt = nextTable) == null ||
                    transferIndex <= 0)
                    break;
                if (U.compareAndSwapInt(this, SIZECTL, sc, sc + 1))
                    transfer(tab, nt);
            }
            else if (U.compareAndSwapInt(this, SIZECTL, sc,
                                         (rs << RESIZE_STAMP_SHIFT) + 2))
                transfer(tab, null);
            s = sumCount();
        }
    }
}

通過Unsafe.compareAndSwapInt修改sizeCtl值,保證只有一個執行緒能夠初始化nextTable,擴容後的陣列長度為原來的兩倍,但是容量是原來的1.5。

節點從table移動到nextTable,大體思想是遍歷、複製的過程。

  1. 首先根據運算得到需要遍歷的次數i,然後利用tabAt方法獲得i位置的元素f,初始化一個forwardNode例項fwd。
  2. 如果f == null,則在table中的i位置放入fwd,這個過程是採用Unsafe.compareAndSwapObjectf方法實現的,很巧妙的實現了節點的併發移動。
  3. 如果f是連結串列的頭節點,就構造一個反序連結串列,把他們分別放在nextTable的i和i+n的位置上,移動完成,採用Unsafe.putObjectVolatile方法給table原位置賦值fwd。
  4. 如果f是TreeBin節點,也做一個反序處理,並判斷是否需要untreeify,把處理的結果分別放在nextTable的i和i+n的位置上,移動完成,同樣採用Unsafe.putObjectVolatile方法給table原位置賦值fwd。

遍歷過所有的節點以後就完成了複製工作,把table指向nextTable,並更新sizeCtl為新陣列大小的0.75倍 ,擴容完成。

紅黑樹構造

注意:如果連結串列結構中元素超過TREEIFY_THRESHOLD閾值,預設為8個,則把連結串列轉化為紅黑樹,提高遍歷查詢效率。

if (binCount != 0) {
    if (binCount >= TREEIFY_THRESHOLD)
        treeifyBin(tab, i);
    if (oldVal != null)
        return oldVal;
    break;
}

接下來我們看看如何構造樹結構,程式碼如下:

private final void treeifyBin(Node<K,V>[] tab, int index) {
    Node<K,V> b; int n, sc;
    if (tab != null) {
        if ((n = tab.length) < MIN_TREEIFY_CAPACITY)
            tryPresize(n << 1);
        else if ((b = tabAt(tab, index)) != null && b.hash >= 0) {
            synchronized (b) {
                if (tabAt(tab, index) == b) {
                    TreeNode<K,V> hd = null, tl = null;
                    for (Node<K,V> e = b; e != null; e = e.next) {
                        TreeNode<K,V> p =
                            new TreeNode<K,V>(e.hash, e.key, e.val,
                                              null, null);
                        if ((p.prev = tl) == null)
                            hd = p;
                        else
                            tl.next = p;
                        tl = p;
                    }
                    setTabAt(tab, index, new TreeBin<K,V>(hd));
                }
            }
        }
    }
}

可以看出,生成樹節點的程式碼塊是同步的,進入同步程式碼塊之後,再次驗證table中index位置元素是否被修改過。
1、根據table中index位置Node連結串列,重新生成一個hd為頭結點的TreeNode連結串列。
2、根據hd頭結點,生成TreeBin樹結構,並把樹結構的root節點寫到table的index位置的記憶體中,具體實現如下:

TreeBin(TreeNode<K,V> b) {
    super(TREEBIN, null, null, null);
    this.first = b;
    TreeNode<K,V> r = null;
    for (TreeNode<K,V> x = b, next; x != null; x = next) {
        next = (TreeNode<K,V>)x.next;
        x.left = x.right = null;
        if (r == null) {
            x.parent = null;
            x.red = false;
            r = x;
        }
        else {
            K k = x.key;
            int h = x.hash;
            Class<?> kc = null;
            for (TreeNode<K,V> p = r;;) {
                int dir, ph;
                K pk = p.key;
                if ((ph = p.hash) > h)
                    dir = -1;
                else if (ph < h)
                    dir = 1;
                else if ((kc == null &&
                          (kc = comparableClassFor(k)) == null) ||
                         (dir = compareComparables(kc, k, pk)) == 0)
                    dir = tieBreakOrder(k, pk);
                    TreeNode<K,V> xp = p;
                if ((p = (dir <= 0) ? p.left : p.right) == null) {
                    x.parent = xp;
                    if (dir <= 0)
                        xp.left = x;
                    else
                        xp.right = x;
                    r = balanceInsertion(r, x);
                    break;
                }
            }
        }
    }
    this.root = r;
    assert checkInvariants(root);
}

主要根據Node節點的hash值大小構建二叉樹。這個紅黑樹的構造過程實在有點複雜,感興趣的同學可以看看原始碼。

get操作

get操作和put操作相比,顯得簡單了許多。

public V get(Object key) {
    Node<K,V>[] tab; Node<K,V> e, p; int n, eh; K ek;
    int h = spread(key.hashCode());
    if ((tab = table) != null && (n = tab.length) > 0 &&
        (e = tabAt(tab, (n - 1) & h)) != null) {
        if ((eh = e.hash) == h) {
            if ((ek = e.key) == key || (ek != null && key.equals(ek)))
                return e.val;
        }
        else if (eh < 0)
            return (p = e.find(h, key)) != null ? p.val : null;
        while ((e = e.next) != null) {
            if (e.hash == h &&
                ((ek = e.key) == key || (ek != null && key.equals(ek))))
                return e.val;
        }
    }
    return null;
}
  1. 判斷table是否為空,如果為空,直接返回null。
  2. 計算key的hash值,並獲取指定table中指定位置的Node節點,通過遍歷連結串列或則樹結構找到對應的節點,返回value值。