1. 程式人生 > >ConcurrentHashMap源碼

ConcurrentHashMap源碼

.com rac fabs amp () col swa ceo ppr

putval源碼

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; //如果table還沒有初始化 if (tab == null || (n = tab.length) == 0) tab = initTable(); //傳入參數tab類與偏移地址(n-1)&hash,通過CAS方法獲取對應目標的值,f,如果對應目標為空,就直接插入 else if ((f = tabAt(tab, i = (n - 1) & hash)) == null) {
// CAS 進行插入,參數(類,偏移地址,預測值,當前值) if (casTabAt(tab, i, null, new Node<K,V>(hash, key, value, null))) break; // no lock when adding to empty bin 沒有鎖,如果是空bin的話 } //如果在進行擴容,則先進行擴容操作??????????????????????????????
else if ((fh = f.hash) == MOVED) tab = helpTransfer(tab, f); //hash沖突 else { V oldVal = null; //在桶子上加鎖,每一個桶子都可以是一個鎖 synchronized (f) { if (tabAt(tab, i) == f) { //fh>=0說明,說明是一個鏈表 if (fh >= 0) { //統計鏈表的長度,看是否需要轉變為一個紅黑樹 binCount = 1; //循環查找 for (Node<K,V> e = f;; ++binCount) { K ek; //找到相同的key 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; //沒找到相同的key,在最後加上新節點 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; } } } } if (binCount != 0) { //是否可以轉變為紅黑樹的條件 if (binCount >= TREEIFY_THRESHOLD) //根據table,和偏移量轉換一個桶子後面的鏈表為紅黑樹 treeifyBin(tab, i); //返回舊的value值 if (oldVal != null) return oldVal; break; } } } //統計size,並且檢查是否需要擴容 addCount(1L, binCount); return null; }

inittable()

    private final Node<K,V>[] initTable() {
        Node<K,V>[] tab; int sc;
        //檢查是否為空
        while ((tab = table) == null || tab.length == 0) {
            if ((sc = sizeCtl) < 0)     //sizeCtl<0表示其他線程已經在初始化了或者擴容了,掛起當前線程 
                Thread.yield(); // lost initialization race; just spin
            else if (U.compareAndSwapInt(this, SIZECTL, sc, -1)) {      //將SIZECTL置為-1,表示有一個線程正在初始化table
                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;
    }

ConcurrentHashMap源碼