Java8 ConcurrentHashMap和ConcurrentLinkedQueue对无锁的应用

Java8 中对并发包中的数据结构增加了很多CAS操作,下面来分析下ConcurrentHashMap和ConcurrentLinkedQueue的增加节点操作中用到的CAS操作。

ConcurrentHashMap put(K key, V value)

java8 中的ConcurrentHashMap相较于Java7有较大的改动,采用CAS和schronized对每个哈希链进行操作。插入节点的时候,如果是在哈希表中插入,则用cas判断是否插入成功,如果在链表中插值,则将该哈希链表加锁,再遍历插值。

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)))    
// 当Key哈希到哈希表中对应的位置,使用cas操作判断其是否null,这里注意,这里对同一个位置进行了两次判断,
// 第一次判断其是否为空,如果为空则采用cas写操作。注意这里的两次判断不能合为一次,如果一开始就用cas写该位置,
// 假如这个位置原本有值就永远写不进去,直到该位置被清空,第二次判断实质是判断是否有并发线程改写此位置。
                    break;                   // no lock when adding to empty bin
            }
            else if ((fh = f.hash) == MOVED)
                tab = helpTransfer(tab, f);    // hashMap扩容
            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)))) {
// 如果Key存在,则将其对应的value改写,这个步骤是加锁的
                                    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)
                        treeifyBin(tab, i);
                    if (oldVal != null)
                        return oldVal;
                    break;
                }
            }
        }
        addCount(1L, binCount);
        return null;
    }

 

ConcurrentLinkedQueue add(K key, V value)

 

public boolean offer(E e) {
        checkNotNull(e);
        final Node<E> newNode = new Node<E>(e);

        for (Node<E> t = tail, p = t;;) {
            Node<E> q = p.next;
// 当p是尾节点时
            if (q == null) {
                // p is last node
// 用CAS操作将新节点查到尾部,如果插入失败则重复尝试
                if (p.casNext(null, newNode)) {
                    // Successful CAS is the linearization point
                    // for e to become an element of this queue,
                    // and for newNode to become "live".
                    if (p != t) // hop two nodes at a time
                        casTail(t, newNode);  // Failure is OK.
                    return true;
                }
                // Lost CAS race to another thread; re-read next
            }
// 此分支与哨兵有关,没太看懂
            else if (p == q)
                // We have fallen off list.  If tail is unchanged, it
                // will also be off-list, in which case we need to
                // jump to head, from which all live nodes are always
                // reachable.  Else the new tail is a better bet.
                p = (t != (t = tail)) ? t : head;
// 当p不是尾节点时,此时尾节点t被重置,则将t给p;此时t不是尾节点时,取下一个节点,每两次更新一次t
            else
                // Check for tail updates after two hops.
                p = (p != t && t != (t = tail)) ? t : q;
        }
    }

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值