一、存储结构
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 说明正在初始化
-
-N 说明有N-1个线程正在进行扩容
-
表示 table 初始化大小, 如果 table 没有初始化
-
表示 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; }
-
根据 key 计算出 hash值
-
判断桶是否为空,为空进行初始化
-
如果当前 key 定位出的Node为空表示可以写入数据
-
如果当前位置的 hashcode == MOVED == -1,则需要进行扩容
-
如果都不满足,则在 syncronized 上锁写入数据
-
如果数量大于 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; }
-
根据hash值计算位置。
-
查找到指定位置,如果头节点就是,直接返回对应的value。
-
如果头节点 hash < 0,说明正在扩容或者是红黑树,查找。
-
如果是链表,遍历查找。
三、JDK1.8的改动
JDK 1.7 使用分段锁机制来实现并发更新操作,核心类为 Segment,它继承自重入锁 ReentrantLock,并发度与 Segment 数量相等。
JDK 1.8 使用了 CAS 操作来支持更高的并发度,在 CAS 操作失败时使用内置锁 synchronized。
并且 JDK 1.8 的实现也在链表过长时会转换为红黑树。