onlyit onlyifabsent( 九 )


onlyit onlyifabsent

文章插图

当第二次进入 i<0 的时候,因为 finishing 为 true,会把几个关键变量重新初始化然后退出
还记得前文问过一个问题吗,(fh = f.hash) == MOVED 这个条件什么时候会执行到
是的,最后一遍检查的时候会执行到
其实最后一遍检查在阿轩看来是多余的,只是老爷子比较谨慎,所以又检查了一遍,然后阿轩去查阅了一波资料,发现还真有人就这个问题问过 Doug,地址http://cs.oswego.edu/pipermail/concurrency-interest/2020-July/017171.html,Doug是这样回复的
Yes, this is a valid point; thanks. The post-scan was needed in a previous version, and could be removed. It does not trigger often enough to matter though, so is for now another minor tweak that might be included next time CHM is updated.
话里的意思也说了,确实是没有必要的,后面可能会做调整
getpublic 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)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 方法的整个脉络再来看 get 方法就简单很多了,因为 Node 的 val 是通过 volatile 修饰的
static class Node<K,V> implements Map.Entry<K,V> {final int hash;final K key;volatile V val;volatile Node<K,V> next;}所以直接对节点进行遍历,符合就返回,没有就返回 null
最后再看一下计算集合容量的方法
sumCountfinal long sumCount() {CounterCell[] as = counterCells; CounterCell a;long sum = baseCount;if (as != null) {for (int i = 0; i < as.length; ++i) {if ((a = as[i]) != null)sum += a.value;}}return sum;}也很简单,就是把 baseCount 和 CounterCell 数组的值加一下
后记通过对 ConcurrentHashMap 源码的学习,我们发现作者使用了很多技巧,这些技巧很值得我们学习和借鉴,所以,平时没事的时候可以多翻翻源码,总会有所收货的


特别声明:本站内容均来自网友提供或互联网,仅供参考,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。