ConcurrentHashMap底层数据结构与源码

一、存储结构

ConcurrentHashMap中的阈值与HashMap中相同

 

可以发现 Java8 的 ConcurrentHashMap 相对于 Java7 来说变化比较大,不再是之前的 Segment 数组 +

HashEntry 数组 + 链表,而是 Node 数组 + 链表/红黑树。当冲突链表达到一定长度时,链表会转换成红黑树。

ConcurrentHashMap在结构上和 Java8 的 HashMap 基本上一样,不过它保证了线程安全性。

二、源码分析

初始化函数initTable

 private final java.util.concurrent.ConcurrentHashMap.Node<K,V>[] initTable() {
         java.util.concurrent.ConcurrentHashMap.Node<K,V>[] tab; int sc;
         // 列表为空
         while ((tab = table) == null || tab.length == 0) {
             // 如果sizeCtl < 0,说明另外的线程执行 CAS 成功,正在进行初始化。
             if ((sc = sizeCtl) < 0)
                 // 让出 CPU 使用权
                 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")
                         java.util.concurrent.ConcurrentHashMap.Node<K,V>[] nt = (java.util.concurrent.ConcurrentHashMap.Node<K,V>[])new java.util.concurrent.ConcurrentHashMap.Node<?,?>[n];
                         table = tab = nt;
                         sc = n - (n >>> 2);
                     }
                 } finally {
                     sizeCtl = sc;
                 }
                 break;
             }
         }
         return tab;
     }

从源码中可以发现 ConcurrentHashMap 的初始化是通过自旋和 CAS 操作完成的。里面需要注意的是变量 sizeCtl ,它的值决定着当前的初始化状态。

  1. -1 说明正在初始化

  2. -N 说明有N-1个线程正在进行扩容

  3. 表示 table 初始化大小, 如果 table 没有初始化

  4. 表示 table 扩容阈值,如果 table 已经初始化。

put函数

 public V put(K key, V value) {
         return putVal(key, value, false);
     }
 final V putVal(K key, V value, boolean onlyIfAbsent) {
         // key 和 value 不能为空
         if (key == null || value == null) throw new NullPointerException();
         int hash = spread(key.hashCode());
         int binCount = 0; // 桶中元素的大小,如果 binCOunt >= 8,转换为红黑树
         for (java.util.concurrent.ConcurrentHashMap.Node<K,V>[] tab = table;;) {
             // f = 目标位置元素
             java.util.concurrent.ConcurrentHashMap.Node<K,V> f; int n, i, fh;
             if (tab == null || (n = tab.length) == 0)
                 // 数组桶为空,初始化数组桶(自旋 + CAS)
                 tab = initTable();
             else if ((f = tabAt(tab, i = (n - 1) & hash)) == null) {
                 // 桶内为空,CAS放入,不加锁,成功了就直接break跳出。
                 if (casTabAt(tab, i, null,
                         new java.util.concurrent.ConcurrentHashMap.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 加锁
                 synchronized (f) {
                     if (tabAt(tab, i) == f) {
                         if (fh >= 0) {     // 大于0表示桶是链表 TREEBIN   = -2 桶是红黑树
                             binCount = 1;
                             for (java.util.concurrent.ConcurrentHashMap.Node<K,V> e = f;; ++binCount) {
                                 K ek;
                   // 如果hash和key都和已存在的元素相等则根据onlyIfAbsebt的值,确定是用之前的值还是新值覆盖
                                 if (e.hash == hash &&
                                         ((ek = e.key) == key ||
                                                 (ek != null && key.equals(ek)))) {
                                     oldVal = e.val;
                                     // 如果 onlyIfAbsent 为 false ,新值覆盖旧值
                                     if (!onlyIfAbsent)
                                         e.val = value;
                                     break;
                                 }
                                 // 链表最末尾的值作为新值的前一个元素
                                 java.util.concurrent.ConcurrentHashMap.Node<K,V> pred = e;
                                 // 如果已经到了末尾值,则创建新的node存放此次插入的key/value
                                 if ((e = e.next) == null) {
                                     pred.next = new java.util.concurrent.ConcurrentHashMap.Node<K,V>(hash, key,
                                             value, null);
                                     break;
                                 }
                             }
                         }
                         // 如果是红黑树做红黑树的插入
                         else if (f instanceof java.util.concurrent.ConcurrentHashMap.TreeBin) {
                             java.util.concurrent.ConcurrentHashMap.Node<K,V> p;
                             binCount = 2;
                             if ((p = ((java.util.concurrent.ConcurrentHashMap.TreeBin<K,V>)f).putTreeVal(hash, key,
                                     value)) != null) {
                                 oldVal = p.val;
                                 if (!onlyIfAbsent)
                                     p.val = value;
                             }
                         }
                     }
                 }
                 // 如果不等于0判断是否需要旋转为红黑树
                 if (binCount != 0) {
                     // 如果大于8则旋转为红黑树
                     if (binCount >= TREEIFY_THRESHOLD)
                         // 旋转为红黑树
                         treeifyBin(tab, i);
                     if (oldVal != null)
                         return oldVal;
                     break;
                 }
             }
         }
         addCount(1L, binCount);
         return null;
     }
  1. 根据 key 计算出 hash值

  2. 判断桶是否为空,为空进行初始化

  3. 如果当前 key 定位出的Node为空表示可以写入数据

  4. 如果当前位置的 hashcode == MOVED == -1,则需要进行扩容

  5. 如果都不满足,则在 syncronized 上锁写入数据

  6. 如果数量大于 TREEIFY_THRESHOLD 则转换成红黑树

get函数

 public V get(Object key) {
         java.util.concurrent.ConcurrentHashMap.Node<K,V>[] tab; java.util.concurrent.ConcurrentHashMap.Node<K,V> e, p; int n, eh; K ek;
         // 判断 key 所在的 hash 位置
         int h = spread(key.hashCode());
         // 如果指定位置存在元素
         if ((tab = table) != null && (n = tab.length) > 0 &&
                 (e = tabAt(tab, (n - 1) & h)) != null) {
             // 头节点 hash 值相同
             if ((eh = e.hash) == h) {
                 if ((ek = e.key) == key || (ek != null && key.equals(ek)))
                     // key hash 值相等,key值相同,直接返回元素 value
                     return e.val;
             }
             else if (eh < 0)
                 // 头结点hash值小于0,说明正在扩容或者是红黑树,find查找
                 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. 根据hash值计算位置。

  2. 查找到指定位置,如果头节点就是,直接返回对应的value。

  3. 如果头节点 hash < 0,说明正在扩容或者是红黑树,查找。

  4. 如果是链表,遍历查找。

三、JDK1.8的改动

JDK 1.7 使用分段锁机制来实现并发更新操作,核心类为 Segment,它继承自重入锁 ReentrantLock,并发度与 Segment 数量相等。

JDK 1.8 使用了 CAS 操作来支持更高的并发度,在 CAS 操作失败时使用内置锁 synchronized。

并且 JDK 1.8 的实现也在链表过长时会转换为红黑树。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值