重要属性和类
sizeCtl
容量控制标识符,在不同的地方有不同用途,而且它的取值不同,也代表不同的含义。
- 负数代表正在进行初始化或扩容操作
- -1代表正在初始化
- -N 表示有N-1个线程正在进行扩容操作
正数或0代表hash冲突链表还没有被初始化,这个数值表示初始化或下一次进行扩容的大小,这一点类似于扩容阈值的概念。后面可以看到,它的值始终是当前ConcurrentHashMap容量的0.75倍,这与loadfactor是对应的。
basecount
hashmap中的元素个数 利用CAS锁进行更新
TreeNode
当链表长度过长的时候,会转换为TreeNode。与HashMap不相同的是,它并不是直接转换为红黑树,而是把这些结点包装成TreeNode放在TreeBin对象中,由TreeBin完成对红黑树的包装。
TreeBin
树化后的ConcurrentHashMap数组,存放的是TreeBin对象,而不是TreeNode对象。
Unsafe与CAS
在ConcurrentHashMap中,随处可以看到U, 大量使用了U.compareAndSwap的方法,这个方法是利用一个CAS算法实现无锁化的修改值的操作,可以大大降低锁代理的性能消耗。
put
/** 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) { //bin链表空,利用cas进行无锁线程安全操作 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) { //bin中node超过门限,树化 if (binCount >= TREEIFY_THRESHOLD) treeifyBin(tab, i); if (oldVal != null) return oldVal; break; } } } //当前ConcurrentHashMap的元素个数+1, addCount(1L, binCount); return null; }
初始化
同jdk1.8版hashtable的lazy-load模式,put时初始化。
利用CAS+volatile保证无锁线程安全的初始化操作。
private final Node<K,V>[] initTable() { Node<K,V>[] tab; int sc; while ((tab = table) == null || tab.length == 0) { //volatile的sizeCtl作为互斥手段,发现竞争性初始化,则spin(自旋) if ((sc = sizeCtl) < 0) Thread.yield(); // lost initialization race; just spin ///cas设置排他标志,如果返回true,进入初始化 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; }
addCount
/** * Adds to count, and if table is too small and not already * * resizing, initiates transfer. If already resizing, helps * * perform transfer if work is available. Rechecks occupancy * * after a transfer to see if another resize is already needed * * because resizings are lagging additions. * * @param x the count to add * @param check if <0, don't check resize, if <= 1 only check if uncontended */ //这个方法一共做了两件事,更新baseCount的值,检测是否进行扩容 // 从 putVal 传入的参数是 1, binCount private final void addCount(long x, int check) { CounterCell[] as; long b, s; //利用CAS方法更新baseCount的值 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(); } // 是否需要扩容,在 putVal 方法调用传参时,默认(hash冲突)要检查 if (check >= 0) { Node<K,V>[] tab, nt; int n, sc; //map的size大于sizeCtl(门限), 且 //table非空,且 //table长度小于最大容量 //则扩容 while (s >= (long)(sc = sizeCtl) && (tab = table) != null && (n = tab.length) < MAXIMUM_CAPACITY) { int rs = resizeStamp(n);//扩容时间戳,用于防止长时间循环扩容 if (sc < 0) {//sizeCtl<0,表示正在扩容 // 如果 sc 的低 16 位不等于 标识符(校验异常 sizeCtl 变化了) // 如果 sc == 标识符 + 1 (扩容结束了,不再有线程进行扩容)(默认第一个线程设置 sc ==rs 左移 16 位 + 2,当第一个线程结束扩容了,就会将 sc 减一。这个时候,sc 就等于 rs + 1) // 如果 sc == 标识符 + 65535(帮助线程数已经达到最大) // 如果 nextTable == null(结束扩容了) // 如果 transferIndex <= 0 (转移状态变化了) // 结束循环 if ((sc >>> RESIZE_STAMP_SHIFT) != rs || sc == rs + 1 || sc == rs + MAX_RESIZERS || (nt = nextTable) == null || transferIndex <= 0) break; // 如果可以帮助扩容,那么将 sc 加 1. 表示多了一个线程在帮助扩容 if (U.compareAndSwapInt(this, SIZECTL, sc, sc + 1)) transfer(tab, nt);//扩容 } //如果不在扩容,将 sc 更新:标识符左移 16 位 然后 + 2. //也就是变成一个负数。高 16 位是标识符,低 16 位初始是 2. else if (U.compareAndSwapInt(this, SIZECTL, sc, (rs << RESIZE_STAMP_SHIFT) + 2)) // 更新 sizeCtl 为负数后,开始扩容。 transfer(tab, null); s = sumCount(); } } }
参考
https://www.cnblogs.com/williamjie/p/9099861.html
《Java核心技术36讲》 杨晓峰
来源:https://www.cnblogs.com/ChengzhiYang/p/12402605.html