ConcurentHashMap

359 阅读3分钟

JDK1.7

image.png

JDK1.8

//CHM初始化(一个16个节点的node数组)
private final Node<K,V>[] initTable() {
    Node<K,V>[] tab; int sc;
    while ((tab = table) == null || tab.length == 0) {
        if ((sc = sizeCtl) < 0)
            Thread.yield(); // 已经有线程把sizeCtl赋值为-1了,此线程通过Thread.yield();释放CPU时间片
        else if (U.compareAndSwapInt(this, SIZECTL, sc, -1)) { //设置SIZECTL为-1
            try {
                if ((tab = table) == null || tab.length == 0) { //(tab = table) 把全局变量赋值给本地变量,为了提升性能
                    int n = (sc > 0) ? sc : DEFAULT_CAPACITY; //DEFAULT_CAPACITY=16 
                    @SuppressWarnings("unchecked")
                    Node<K,V>[] nt = (Node<K,V>[])new Node<?,?>[n];
                    table = tab = nt;
                    sc = n - (n >>> 2);//无符合右移两位 扩容因子:16*0.75
                }
            } finally {
                sizeCtl = sc;
            }
            break;
        }
    }
    return tab;
}

put方法

image.png

//假设put("xiaofeng","架构师");
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(); //1.第一步初始化node数组
        else if ((f = tabAt(tab, i = (n - 1) & hash)) == null) { // 2,(n - 1) & hash) 位置计算,会得到一个下标值,下标值可能是0~15中任何一个值
            if (casTabAt(tab, i, null, new Node<K,V>(hash, key, value, null))) //当下标i位置的值为null的时候,就替换成一个new Node<"xiaofeng","架构师"> 注意不要把node<k,v>当做一个hashmap,它只是hashmap中一个底层的数据节点
                break;                   // no lock when adding to empty bin
        }
        else if ((fh = f.hash) == MOVED)
            tab = helpTransfer(tab, f);
        else {
            V oldVal = null;
            synchronized (f) { //当前要赋值的节点已经有值了,存在哈希冲突,此时要锁住节点f,因为有可能同时有其他数据也哈希到此节点上了,
                if (tabAt(tab, i) == f) {
                    if (fh >= 0) { //fh在前面已经赋值了,表示f的hash值
                        binCount = 1;
                        for (Node<K,V> e = f;; ++binCount) {
                            K ek;
                            if (e.hash == hash &&
                                ((ek = e.key) == key ||
                                 (ek != null && key.equals(ek)))) { //这个if其实相同的Key,需要把value覆盖. [存在hash冲突的可能是同一个key]
                                oldVal = e.val;
                                if (!onlyIfAbsent)
                                    e.val = value;
                                break;
                            }
                            Node<K,V> pred = e; //e表示头节点
                            if ((e = e.next) == null) { //建立一个链表关系【通过链式去解决hash冲突】
                                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)
                    treeifyBin(tab, i);
                if (oldVal != null)
                    return oldVal;
                break;
            }
        }
    }
    addCount(1L, binCount); 
    return null;
}

addCount 两个阶段: 1,初始化阶段 2,并发更新的阶段

private transient volatile long baseCount; //在没有竞争的情况下,通过cas操作更新元素格个数
private transient volatile CounterCell[] counterCells;//存在线程竞争的情况下,存储元素个数

@sun.misc.Contended static final class CounterCell {
    volatile long value;
    CounterCell(long x) { value = x; }
}

final long sumCount() {
    CounterCell[] as = counterCells; CounterCell a;
    long sum = baseCount;
    if (as != null) {
        for (int i = 0; i < as.length; ++i) {
            if ((a = as[i]) != null)
                sum += a.value;
        }
    }
    return sum;
}
size()计算:
public int size() {
    long n = sumCount();
    return ((n < 0L) ? 0 :
            (n > (long)Integer.MAX_VALUE) ? Integer.MAX_VALUE :
            (int)n);
}
原理:baseCount + (遍历CounterCell[]数组中每个CounterCell中的value) = sum 

1).直接去访问baseCount 累加元素个数
2).找到CousnterCell[] 随机的某个下标位置, value=v+x() -> 表示记录元素个数 如果
3).前面都是失败, 则进入到fullAndCount();

private final void addCount(long x, int check) {
    CounterCell[] as; long b, s; //CounterCell[] as 定义局部变量,提升访问性能
    if ((as = counterCells) != null ||
        !U.compareAndSwapLong(this, BASECOUNT, b = baseCount, s = b + x)) { //修改b=b+x 添加失败走下面逻辑
        CounterCell a; long v; int m;
        boolean uncontended = true;
        
        //ThreadLocalRandom.getProbe() & m ,随机函数与上m(数组长度)得到一个数组下标。
        //
        if (as == null || (m = as.length - 1) < 0 ||  
            (a = as[ThreadLocalRandom.getProbe() & m]) == null ||
            !(uncontended = U.compareAndSwapLong(a, CELLVALUE, v = a.value, v + x))) { //找到CousnterCell[] 随机的某个下标位置, value=v+x() [表示记录元素个数]
            fullAddCount(x, uncontended); //如果前面都是失败, 则进入到fullAndCount();
            return;
        }
        if (check <= 1)
            return;
        s = sumCount();
    }
    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();
        }
    }
}

//复制fullAndCount部分代码


for (;;) {
    CounterCell[] as; CounterCell a; int n; long v;
    //已经初始化后自旋后进入第一个if
    if ((as = counterCells) != null && (n = as.length) > 0) {
        if ((a = as[(n - 1) & h]) == null) {
            if (cellsBusy == 0) {         
                CounterCell r = new CounterCell(x); 
                if (cellsBusy == 0 &&
                    U.compareAndSwapInt(this, CELLSBUSY, 0, 1)) {
                    boolean created = false;
                    try {               // Recheck under lock
                        CounterCell[] rs; int m, j;
                        if ((rs = counterCells) != null &&
                            (m = rs.length) > 0 &&
                            rs[j = (m - 1) & h] == null) {
                            rs[j] = r;
                            created = true;
                        }
                    } finally {
                        cellsBusy = 0;
                    }
                    if (created)
                        break;
                    continue;           // Slot is now non-empty
                }
            }
            collide = false;
        }
        else if (!wasUncontended)       // CAS already known to fail
            wasUncontended = true;      // Continue after rehash
        else if (U.compareAndSwapLong(a, CELLVALUE, v = a.value, v + x)) //如果某下标元素不为空,就修改v=v+x
            break;
        else if (counterCells != as || n >= NCPU)
            collide = false;            // At max size or stale
        else if (!collide)
            collide = true;
        else if (cellsBusy == 0 &&
                 U.compareAndSwapInt(this, CELLSBUSY, 0, 1)) {
            try {
                //存在竞争的情况下扩容
                if (counterCells == as) {// Expand table unless stale
                    CounterCell[] rs = new CounterCell[n << 1]; //<<1 扩容一倍[比如2变成4]
                    for (int i = 0; i < n; ++i)
                        rs[i] = as[i];
                    counterCells = rs;
                }
            } finally {
                cellsBusy = 0;
            }
            collide = false;
            continue;                   // Retry with expanded table
        }
        h = ThreadLocalRandom.advanceProbe(h);
    }
    //进到这里面的时候counterCells为null了,cellsBusy=0表示当前没有线程来操作,接下来就是进行一个占位[把cellsBusy改为1]
    else if (cellsBusy == 0 && counterCells == as &&
                     U.compareAndSwapInt(this, CELLSBUSY, 0, 1)) {
        //进入到下面逻辑表示当前线程获得了初始化的资格
        boolean init = false;
        try {                           // Initialize table
            if (counterCells == as) {
                CounterCell[] rs = new CounterCell[2];  //初始化一个长度为2的数组
                rs[h & 1] = new CounterCell(x); //h & 1 hash值与上1还是计算下标的
                counterCells = rs;
                init = true;
            }
        } finally {
            cellsBusy = 0; //相当于释放,有点锁的概念
        }
        if (init)
            break;
    }
    else if (U.compareAndSwapLong(this, BASECOUNT, v = baseCount, v + x))  //
        break;                          // Fall back on using base
}

image.png (addCount图)

扩容

(当元素个数大于阈值的时候) 如果此时正在扩容, 在扩容阶段进来的线程会协助扩容

addCount方法中代码:
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)  //if(true)表示不需要扩容
                break;
            if (U.compareAndSwapInt(this, SIZECTL, sc, sc + 1))
                transfer(tab, nt);//协助扩容
        }
        //表示当前没有线程在扩容
        //rs << RESIZE_STAMP_SHIFT) + 2 : 第一次扩容, + 2
        else if (U.compareAndSwapInt(this, SIZECTL, sc,
                                     (rs << RESIZE_STAMP_SHIFT) + 2))
            transfer(tab, null);
        s = sumCount();
    }
}
static final int resizeStamp(int n) {
    return Integer.numberOfLeadingZeros(n) | (1 << (RESIZE_STAMP_BITS - 1));
}