jdk1.8 ConcurrentHashMap

jdk1.8的ConcurrentHashMap的实现中,构造方法主要是对内部的大小进行设置。

public ConcurrentHashMap(int initialCapacity,
                         float loadFactor, int concurrencyLevel) {
    if (!(loadFactor > 0.0f) || initialCapacity < 0 || concurrencyLevel <= 0)
        throw new IllegalArgumentException();
    if (initialCapacity < concurrencyLevel)   // Use at least as many bins
        initialCapacity = concurrencyLevel;   // as estimated threads
    long size = (long)(1.0 + (long)initialCapacity / loadFactor);
    int cap = (size >= (long)MAXIMUM_CAPACITY) ?
        MAXIMUM_CAPACITY : tableSizeFor((int)size);
    this.sizeCtl = cap;
}
 
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;
}

构造方法中对负载因子,初始化的map容量,以及map对并行度作为构造方法的参数进行验证。保证初始化时候的容量不会小于整个map的并发度。

在HashMap中,map的容量等于负载因子与map大小的积,所以这里用初始化的容量除以负载因子得到初始化的容量。

在容量的选择上通过tableSizFor()方法保证map的大小为2的n次方,通过或运算来保证。
构造方法中没有对真正的存储结构进行初始化,在第一次进行put操作的时候对map中的存储结构进行初始化。

public V put(K key, V value) {
    return putVal(key, value, false);
}
 
/** Implementation for put and putIfAbsent */
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);
        else {
            V oldVal = null;
            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;
                        }
                    }
                }
            }
            if (binCount != 0) {
                if (binCount >= TREEIFY_THRESHOLD)
                    treeifyBin(tab, i);
                if (oldVal != null)
                    return oldVal;
                break;
            }
        }
    }
    addCount(1L, binCount);
    return null;
}

在ConcurrentHashMap中通过table来存储数据,如果是第一次调用put()方法,那么则会需要通过initTable()方法来初始化

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(); // 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;
}

initTable()方法中,首先会通过unsafe来通过cas来将原本存放初始化大小的sizectl参数设为-1,表示table正在初始化当中。之后以刚才构造方法中的得到的大小来生成该大小的node数组来作为存储结构。

在完成了node数组的创建之后,则sizectl参数不再存放该map中数组大小,而是保存当负载因子为0.75情况下,当前数组大小情况下的数组容量。

在initTable()方法完成了table的初始化之后,保证了node数组存在之后,则需要根据要put的key 对应hash取得node数组上对应的位置。通过tabAt()方法根据数组大小与hash相与的结果得到在数组上的位置。

static final <K,V> Node<K,V> tabAt(Node<K,V>[] tab, int i) {
    return (Node<K,V>)U.getObjectVolatile(tab, ((long)i << ASHIFT) + ABASE);
}

SHIFT和ABASE的具体大小的获得可以在unsafe类的静态块里可以看到
ABASE实是node数组在内存中第一个元素的偏移量,ASHIFT则是单个数组成员相对前一个成员的偏移量。所以,通过unsafe定位得到相应位置上Node数组上的信息。

Class<?> ak = Node[].class;
ABASE = U.arrayBaseOffset(ak);
int scale = U.arrayIndexScale(ak);
if ((scale & (scale - 1)) != 0)
    throw new Error("data type scale not a power of two");
ASHIFT = 31 - Integer.numberOfLeadingZeros(scale);

如果这一位置为null,说明位置为空,直接通过cas将新创建的node节点赋值在该位置上。
如果该节点的hash为-1,说明此时map处于扩容阶段,会通过helpTransfer()方法来帮助扩容。

如果数组上的位置已经存在相应节点,就会从头开始,在链表中从头开始往后不断对比key,如果出现所需要put进来的key,那么只需要将新value赋值到原位即可,否则会创建一个新Node节点加载链表的最后。
但如果该数组这一位置上的节点已经TreeBin类型的,那么说明这一位置已经使用红黑树来存储,那么调用putTreeVal()向红黑树中插入这一节点。

完成红黑树转化之后调用addCount()方法,判断map是否需要扩容。

private final void addCount(long x, int check) {
    CounterCell[] as; long b, s;
    if ((as = counterCells) != null ||
        !U.compareAndSwapLong(this, BASECOUNT, b = baseCount, s = b + x)) {
        CounterCell a; long v; int m;
        boolean uncontended = true;
        if (as == null || (m = as.length - 1) < 0 ||
            (a = as[ThreadLocalRandom.getProbe() & m]) == null ||
            !(uncontended =
              U.compareAndSwapLong(a, CELLVALUE, v = a.value, v + x))) {
            fullAddCount(x, uncontended);
            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();
        }
    }
}
 
static final int resizeStamp(int n) {
    return Integer.numberOfLeadingZeros(n) | (1 << (RESIZE_STAMP_BITS - 1));
}

在addCount()方法中先将刚才put方法加进在map里的元素个数通过unsafe用cas加在baseCount字段上,也就是代表这个map中现有的元素个数上。然后,由于在之前的initTable()方法中,已经对sizectl参数,从初始化所需要的大小转化为此时table中在默认负载因子下的容量,所以此时的元素个数若是大于sizectl参数,那么这个map则需要开始扩容。

但是,由于在扩容的时候会把sizeCtl的大小设为-n,所以此时若是sizeCtl的大小已经小于0,那么说明已经有别的线程开始给这个map扩容了。

若是没有。则说明此时该线程是在这一情况下第一个开始发起扩容步骤的线程。

在扩容之前需要更新sizectl的大小,保证之后的线程在准备扩容的时候,能够意识到已经有线程已经开始扩容,首先会调用resizeStamp()方法获得扩容前大小在32位下高位0的个数与2的15次相或的结果,之后继续左移15位再加2,得到的结果赋值给sizeCtl,生成的戳用来代表这一次的扩容,防止扩容重叠。那么则开始调用transfer()方法开始Map的扩容。

private final void transfer(Node<K,V>[] tab, Node<K,V>[] nextTab) {
    int n = tab.length, stride;
    if ((stride = (NCPU > 1) ? (n >>> 3) / NCPU : n) < MIN_TRANSFER_STRIDE)
        stride = MIN_TRANSFER_STRIDE; // subdivide range
    if (nextTab == null) {            // initiating
        try {
            @SuppressWarnings("unchecked")
            Node<K,V>[] nt = (Node<K,V>[])new Node<?,?>[n << 1];
            nextTab = nt;
        } catch (Throwable ex) {      // try to cope with OOME
            sizeCtl = Integer.MAX_VALUE;
            return;
        }
        nextTable = nextTab;
        transferIndex = n;
    }
    int nextn = nextTab.length;
    ForwardingNode<K,V> fwd = new ForwardingNode<K,V>(nextTab);
    boolean advance = true;
    boolean finishing = false; // to ensure sweep before committing nextTab
    for (int i = 0, bound = 0;;) {
        Node<K,V> f; int fh;
        while (advance) {
            int nextIndex, nextBound;
            if (--i >= bound || finishing)
                advance = false;
            else if ((nextIndex = transferIndex) <= 0) {
                i = -1;
                advance = false;
            }
            else if (U.compareAndSwapInt
                     (this, TRANSFERINDEX, nextIndex,
                      nextBound = (nextIndex > stride ?
                                   nextIndex - stride : 0))) {
                bound = nextBound;
                i = nextIndex - 1;
                advance = false;
            }
        }
        if (i < 0 || i >= n || i + n >= nextn) {
            int sc;
            if (finishing) {
                nextTable = null;
                table = nextTab;
                sizeCtl = (n << 1) - (n >>> 1);
                return;
            }
            if (U.compareAndSwapInt(this, SIZECTL, sc = sizeCtl, sc - 1)) {
                if ((sc - 2) != resizeStamp(n) << RESIZE_STAMP_SHIFT)
                    return;
                finishing = advance = true;
                i = n; // recheck before commit
            }
        }
        else if ((f = tabAt(tab, i)) == null)
            advance = casTabAt(tab, i, null, fwd);
        else if ((fh = f.hash) == MOVED)
            advance = true; // already processed
        else {
            synchronized (f) {
                if (tabAt(tab, i) == f) {
                    Node<K,V> ln, hn;
                    if (fh >= 0) {
                        int runBit = fh & n;
                        Node<K,V> lastRun = f;
                        for (Node<K,V> p = f.next; p != null; p = p.next) {
                            int b = p.hash & n;
                            if (b != runBit) {
                                runBit = b;
                                lastRun = p;
                            }
                        }
                        if (runBit == 0) {
                            ln = lastRun;
                            hn = null;
                        }
                        else {
                            hn = lastRun;
                            ln = null;
                        }
                        for (Node<K,V> p = f; p != lastRun; p = p.next) {
                            int ph = p.hash; K pk = p.key; V pv = p.val;
                            if ((ph & n) == 0)
                                ln = new Node<K,V>(ph, pk, pv, ln);
                            else
                                hn = new Node<K,V>(ph, pk, pv, hn);
                        }
                        setTabAt(nextTab, i, ln);
                        setTabAt(nextTab, i + n, hn);
                        setTabAt(tab, i, fwd);
                        advance = true;
                    }
                    else if (f instanceof TreeBin) {
                        TreeBin<K,V> t = (TreeBin<K,V>)f;
                        TreeNode<K,V> lo = null, loTail = null;
                        TreeNode<K,V> hi = null, hiTail = null;
                        int lc = 0, hc = 0;
                        for (Node<K,V> e = t.first; e != null; e = e.next) {
                            int h = e.hash;
                            TreeNode<K,V> p = new TreeNode<K,V>
                                (h, e.key, e.val, null, null);
                            if ((h & n) == 0) {
                                if ((p.prev = loTail) == null)
                                    lo = p;
                                else
                                    loTail.next = p;
                                loTail = p;
                                ++lc;
                            }
                            else {
                                if ((p.prev = hiTail) == null)
                                    hi = p;
                                else
                                    hiTail.next = p;
                                hiTail = p;
                                ++hc;
                            }
                        }
                        ln = (lc <= UNTREEIFY_THRESHOLD) ? untreeify(lo) :
                            (hc != 0) ? new TreeBin<K,V>(lo) : t;
                        hn = (hc <= UNTREEIFY_THRESHOLD) ? untreeify(hi) :
                            (lc != 0) ? new TreeBin<K,V>(hi) : t;
                        setTabAt(nextTab, i, ln);
                        setTabAt(nextTab, i + n, hn);
                        setTabAt(tab, i, fwd);
                        advance = true;
                    }
                }
            }
        }
    }
}

在tansfer()方法中,首先,会根据原本的node数组大小,生成一个新的两倍大小的node数组,也就说这个数组将是扩容之后新的数组。之后生成一个新的ForwardingNode节点,其中的nextTable字段存放新的node数组,其他参数继承自node类,另外这个节点的hash等于-1,也就是正在处于扩容阶段。

接下来while循环控制所需处理的原数组下标i的大小,通过advance参数来控制是否进入。具体操作中通过调整advance参数的大小来决定是否进行i–操作,若是第一次进入,初始i值应该是原大小-1。
下来会将从原数组的最后一位开始复制,通过下标取得原数组相应位置上的成员,如果是null,就会把之前生成的ForwardingNode节点赋值在原数组这一位置上,保证其他线程在访问原数组这一位置时意识到此处迁移,之后改变advance值,保证i可以在循环体里顺利-1。

若这位置上hash已经是-1,就跳过,说明已经处理过,然后改变advance的值。

若原数组该位置有相应的成员,并且是简单的链表类型的node,则要开始复制在这一位置上的链表。这里新生成的链表将会是原本相应位置上的倒序,同时根据各个节点的与总量的hash的结果判断其是其在新的数组上的位置仍旧是原位置还是原位置加数组大小后的结果。

而如果该节点是红黑树的节点,那么与上面情况类似,根据其hash与原本数组大小相与的结果来判断其在新的位置,由于扩容后各位置上碰撞数量会发生变化,那么就需要判断是否还需要重新转变成链表。

同时,原数组被赋值节点的位置也需要被赋值为ForwardingNode,以免多线程情况下无法得知该该节点的扩容情况。

在所有节点遍历完毕之后,将map的table赋值为新的node数组,sizeCtl通过原大小左移一位减去右移一位的结果来表示默认负载因子下的容量。

同时这里的线程需要离开的时候,会给sc进行-1,来表示线程的离开,同时,在离开时判断sc-2右移16位的值是否与rs相等,显然这里可以在第一次进行扩容之前看到如果是最后一个线程准备离开,那么应该相等,也应该完成扩容最后的检验收尾步骤。扩容就此完毕。

添加、删除节点之处都会检测到table的第i个桶是ForwardingNode的话(查找到的相应下表位置下的hash为-1,则说明该位置在扩容操作中已经被处理过)会调用helpTransfer()方法

final Node<K,V>[] helpTransfer(Node<K,V>[] tab, Node<K,V> f) {
    Node<K,V>[] nextTab; int sc;
    if (tab != null && (f instanceof ForwardingNode) &&
        (nextTab = ((ForwardingNode<K,V>)f).nextTable) != null) {
        int rs = resizeStamp(tab.length);
        while (nextTab == nextTable && table == tab &&
               (sc = sizeCtl) < 0) {
            if ((sc >>> RESIZE_STAMP_SHIFT) != rs || sc == rs + 1 ||
                sc == rs + MAX_RESIZERS || transferIndex <= 0)
                break;
            if (U.compareAndSwapInt(this, SIZECTL, sc, sc + 1)) {
                transfer(tab, nextTab);
                break;
            }
        }
        return nextTab;
    }
    return table;
}

所以说到helpTransfer()方法的话说明一定有线程已经开始扩容了。所以一定能够取得到新的新的node数组,并以此作为参数调用transfer()方法帮助扩容。关于此处sc与rs的检验,sc的无符号右移16位应与rs相等,保证其扩容是出于同一轮的扩容(都是n到n^2),同时sc+1代表扩容的线程数+1,并调用transfer()方法开始扩容。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值