- java.util.concurrent 这个包下面的 类都很经典。
- ConcurrentHashMap 这个类是java中讨论最多的,也是争论最多的类了。很多人对这个类很好奇。这个博客就是用来讲解ConcurrentHashMap
- 作为并发集合,大家比较关心 读写,锁,与 map的散列。
- 读写如何的锁
- get操作( 所有读操作都没加锁。大家可以去看下。)
public V get(Object key) { Node<K,V>[] tab; Node<K,V> e, p; int n, eh; K ek; int h = spread(key.hashCode()); if ((tab = table) != null && (n = tab.length) > 0 && (e = tabAt(tab, (n - 1) & h)) != null) { if ((eh = e.hash) == h) { if ((ek = e.key) == key || (ek != null && key.equals(ek))) return e.val; } else if (eh < 0) // TreeBin 操作 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; }
明显是没有上锁的。包括所有的读操作。都是不上锁的。 - put操作(remove等修改操作)
- 所有读操作是这样一个模式,如果hash桶中坐标没有数据。就使用CAS 操作。如果有数据。就使用synchronized关键字。比起jdk1.7,1.6使用读写锁,代码比较简洁,同样使用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; //为什么要这个循序,大家会很疑惑 //其实很简单,因为多线程操作,然后没有使用锁,使用 unsafe,多个unsafe不是原子性的,在多线程的情况下,会出现问题。所以使用for来解决这个问题 for (Node<K,V>[] tab = table;;) { // f 是节点,n是数组长度,i是hash与数组长度的数组下标,fh是在数组下标已经坐在的节点的hash值 Node<K,V> f; int n, i, fh; if (tab == null || (n = tab.length) == 0) tab = initTable();//延迟初始化 table //通过unsafe 判断 下标是否有 节点 else if ((f = tabAt(tab, i = (n - 1) & hash)) == null) { //如果不存在。就创建一个节点 通过 unsafe加入到数组中,所以读是不加锁的 //注意:如果在多个线程同时加入 hash后同一下标的node,那么只有一个会成功,其他失败。失败的就会在再次循序。 //这是循环解决的问题之一 if (casTabAt(tab, i, null, new Node<K,V>(hash, key, value, null))) break; // no lock when adding to empty bin } //大家很奇怪这个 if是干什么用额,去了解ForwardingNode这个对象 //这个对象在 hash散列的时候用,原来的一个节点会重新散列到 下个表,原来表的节点的hash就成为了 moved 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; } } } //添加 在tree下添加节点 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; } } } } //java8,明确的改革 if (binCount != 0) { //binCount是链表的操作次数,操作多少次。表示链表有多长。当链表大于等于8的时候,链表会变成 tree if (binCount >= TREEIFY_THRESHOLD) treeifyBin(tab, i); if (oldVal != null) return oldVal; break; } } } addCount(1L, binCount); return null; }
- 这里是大家最关心的要点,重新散列,也就是重新hash
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; //为什么要这个循序,大家会很疑惑 //其实很简单,因为多线程操作,然后没有使用锁,使用 unsafe,多个unsafe不是原子性的,在多线程的情况下,会出现问题。所以使用for来解决这个问题 for (Node<K,V>[] tab = table;;) { // f 是节点,n是数组长度,i是hash与数组长度的数组下标,fh是在数组下标已经坐在的节点的hash值 Node<K,V> f; int n, i, fh; if (tab == null || (n = tab.length) == 0) tab = initTable();//延迟初始化 table //通过unsafe 判断 下标是否有 节点 else if ((f = tabAt(tab, i = (n - 1) & hash)) == null) { //如果不存在。就创建一个节点 通过 unsafe加入到数组中,所以读是不加锁的 //注意:如果在多个线程同时加入 hash后同一下标的node,那么只有一个会成功,其他失败。失败的就会在再次循序。 //这是循环解决的问题之一 if (casTabAt(tab, i, null, new Node<K,V>(hash, key, value, null))) break; // no lock when adding to empty bin } //大家很奇怪这个 if是干什么用额,去了解ForwardingNode这个对象 //这个对象在 hash散列的时候用,原来的一个节点会重新散列到 下个表,原来表的节点的hash就成为了 moved 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; } } } //添加 在tree下添加节点 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; } } } } //java8,明确的改革 if (binCount != 0) { //binCount是链表的操作次数,操作多少次。表示链表有多长。当链表大于等于8的时候,链表会变成 tree if (binCount >= TREEIFY_THRESHOLD) treeifyBin(tab, i); if (oldVal != null) return oldVal; break; } } } addCount(1L, binCount); return null; } private final void addCount(long x, int check) { CounterCell[] as; long b, s; //这个判断的目的是 解决 unsafu的死循环问题 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(); } // 有一个问题 ,只有添加操作是 大于0的,那么 没有hash收缩功能 if (check >= 0) { Node<K,V>[] tab, nt; int n, sc; //我靠,这里又有一个循序,是解决什么问题了? //sc也就是 sizeCtl 等于 -1的情况只有,table初始化与序列化的时候。 //这个循环是保证 序列化之后,还可以加入数据,目测是这样,不敢保证。 while (s >= (long)(sc = sizeCtl) && (tab = table) != null && (n = tab.length) < MAXIMUM_CAPACITY) { int rs = resizeStamp(n); // 这个if 基本可以忽略 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(); } } } 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; // good 这个对象,的设计。让散列操不会堵塞 ForwardingNode<K,V> fwd = new ForwardingNode<K,V>(nextTab); boolean advance = true; // 只要过了 第一个 while 基本所有操作都会 advance = true;,每次循环都要进入 while 那么 i 这个值才会改变 boolean finishing = false; // to ensure sweep before committing nextTab for (int i = 0, bound = 0;;) { Node<K,V> f; int fh; //这个 while 真心不怎么明白 //唯一能解释的是,防止散列完成,才知道多线程操作问题,快速知道多线程问题 while (advance) { int nextIndex, nextBound; if (--i >= bound || finishing) advance = false; //这个判断只可能进来一次, else if ((nextIndex = transferIndex) <= 0) { i = -1; advance = false; } //比如 n 等于 128,stride 为 128 >>>3 /8 =2, //i = 128,bound -126,那么每两次就会在进来一次,那么就会知道,(nextIndex = transferIndex) 这操作就会知道多线程在操作 else if (U.compareAndSwapInt (this, TRANSFERINDEX, nextIndex, nextBound = (nextIndex > stride ? nextIndex - stride : 0))) { bound = nextBound; i = nextIndex - 1; advance = false; } } // // 那个操作会让 i 大于等于 n ,这个真想不到 // i + n 也大于等于不了 nextn 啊, //只有一个可能,在强并发下,有两个线程都进入了。进行操作了。没错 // if (i < 0 || i >= n || i + n >= nextn) { int sc; if (finishing) { nextTable = null; table = nextTab; sizeCtl = (n << 1) - (n >>> 1); return; } // 先是 sc -1 这个操作没有错。应该addcont里面的判断是 是需要减一的,没有在addcount减,放到这里,可以减少操作 if (U.compareAndSwapInt(this, SIZECTL, sc = sizeCtl, sc - 1)) { //这个操作会排除 最后进来之前的线程操作。 //怎么做到额,请看addCount方法的 2286行 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 { //只有对节点操作才会上锁,性能非常 //散列这里与其他版本的不同,散列的思路很好,因为每次扩展都是2倍,那么扩张之后的hash,在进行一次移位,等于1的就在原有的地方加上扩展之前的系数(比如 从16扩展到32,那么hash,下标1的桶,这个桶会分裂成2个桶,一个还在1下表,一个在16+1下标。 synchronized (f) { if (tabAt(tab, i) == f) { Node<K,V> ln, hn; if (fh >= 0) { int runBit = fh & n; Node<K,V> lastRun = f; //寻分裂出来的 lastRun 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); } //把两个链表,加入到下个tab setTabAt(nextTab, i, ln); setTabAt(nextTab, i + n, hn); //把分裂的 桶,替换成 fwd 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; } } } } } }
- 看过 jdk8文档的伙计都知道,jdk8,不再是双桶。而进入了 二叉树结构。请看上面的添加操作,与散列操作就知道。TreeBin对象与TreeNode对象就清除了。至于性能怎么样,可以用jdk8文档的标准,性能刚刚的。
- 使用ForwardingNode对象,保证在散列的时候读写操作是在nextbat里面。非常优秀的设计。
- 使用Unsafe 对象在性能上带来疯狂的性能提升,但是也给程序设计带来了,超大的复杂性。
- 实在不喜欢,使用这个编辑器,太麻烦了。
jdk8之ConcurrentHashMap源码解析
猜你喜欢
转载自jahu.iteye.com/blog/2331191
今日推荐
周排行