转载文章,原博客地址为:http://blog.csdn.net/u010887744/article/details/50637030
jdk1.8和jdk1.7对于ConcurrentHashMap的实现出现的重大变化,不再采用分段锁的方法,网上这方面的博客较少,这篇文章写得较好,转载扩撒。
本文首写于有道云笔记,并在小组分享会分享,先整理发布,希望和大家交流探讨。云笔记地址
概述:
1、设计首要目的:维护并发可读性(get、迭代相关);次要目的:使空间消耗比HashMap相同或更好,且支持多线程高效率的初始插入(empty table)。
2、HashTable
线程安全,但采用synchronized,多线程下效率低下。线程1put时,线程2无法put或get。
实现原理:
锁分离:
在HashMap的基础上,将数据分段存储,
ConcurrentHashMap由多个Segment组成,每个Segment都有把锁。Segment下包含很多Node,也就是我们的键值对了。
如果还停留在锁分离、Segment,那已经out了。
Segment虽保留,但已经简化属性,仅仅是为了兼容旧版本。
- CAS算法;unsafe.compareAndSwapInt(this, valueOffset, expect, update); CAS(Compare And Swap),意思是如果valueOffset位置包含的值与expect值相同,则更新valueOffset位置的值为update,并返回true,否则不更新,返回false。
- 与Java8的HashMap有相通之处,底层依然由“数组”+链表+红黑树;
- 底层结构存放的是TreeBin对象,而不是TreeNode对象;
- CAS作为知名无锁算法,那ConcurrentHashMap就没用锁了么?当然不是,hash值相同的链表的头结点还是会synchronized上锁。
private static final int MAXIMUM_CAPACITY = 1 << 30; // 2的30次方=1073741824
private static final intDEFAULT_CAPACITY = 16;
static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8; // MAX_VALUE=2^31-1=2147483647
private static finalint DEFAULT_CONCURRENCY_LEVEL = 16;
private static final float LOAD_FACTOR = 0.75f;
static final int TREEIFY_THRESHOLD = 8; // 链表转树阀值,大于8时
static final int UNTREEIFY_THRESHOLD = 6; //树转链表阀值,小于等于6(tranfer时,lc、hc=0两个计数器分别++记录原bin、新binTreeNode数量,<=UNTREEIFY_THRESHOLD 则untreeify(lo))。【仅在扩容tranfer时才可能树转链表】
static final int MIN_TREEIFY_CAPACITY = 64;
private static final int MIN_TRANSFER_STRIDE = 16;
private static int RESIZE_STAMP_BITS = 16;
private static final int MAX_RESIZERS = (1 << (32 - RESIZE_STAMP_BITS)) - 1; // 2^15-1,help resize的最大线程数
private static final int RESIZE_STAMP_SHIFT = 32 - RESIZE_STAMP_BITS; // 32-16=16,sizeCtl中记录size大小的偏移量
static final int MOVED = -1; // hash for forwarding nodes(forwarding nodes的hash值)、标示位
static final int TREEBIN = -2; // hash for roots of trees(树根节点的hash值)
static final int RESERVED = -3; // hash for transient reservations(ReservationNode的hash值)
static final int HASH_BITS = 0x7fffffff; // usable bits of normal node hash
static final int NCPU = Runtime.getRuntime().availableProcessors(); // 可用处理器数量
/**
* Table initialization and resizing control. When negative, the
* table is being initialized or resized: -1 for initialization,
* else -(1 + the number of active resizing threads). Otherwise,
* when table is null, holds the initial table size to use upon
* creation, or 0 for default. After initialization, holds the
* next element count value upon which to resize the table.
*/
private transient volatile int sizeCtl;
sizeCtl是控制标识符,不同的值表示不同的意义。
- 负数代表正在进行初始化或扩容操作
- -1代表正在初始化
- -N 表示有N-1个线程正在进行扩容操作
- 正数或0代表hash表还没有被初始化,这个数值表示初始化或下一次进行扩容的大小,类似于扩容阈值。它的值始终是当前ConcurrentHashMap容量的0.75倍,这与loadfactor是对应的。实际容量>=sizeCtl,则扩容。
部分构造函数:
- public ConcurrentHashMap(int initialCapacity,
- float loadFactor, int concurrencyLevel) {
- if (!(loadFactor > 0.0f) || initialCapacity < 0 || concurrencyLevel <= 0)
- thrownew IllegalArgumentException();
- if (initialCapacity < concurrencyLevel)
- initialCapacity = concurrencyLevel;
- long size = (long)(1.0 + (long)initialCapacity / loadFactor);
- int cap = (size >= (long)MAXIMUM_CAPACITY) ?
- MAXIMUM_CAPACITY : tableSizeFor((int)size);
- this.sizeCtl = cap;
- }
concurrencyLevel:
concurrencyLevel,能够同时更新ConccurentHashMap且不产生锁竞争的最大线程数,在Java8之前实际上就是ConcurrentHashMap中的分段锁个数,即Segment[]的数组长度
。
正确地估计很重要,当低估,数据结构将根据额外的竞争,从而导致线程试图写入当前锁定的段时阻塞;
相反,如果高估了并发级别,你遇到过大的膨胀,由于段的不必要的数量;
这种膨胀可能会导致性能下降,由于高数缓存未命中。
在Java8里,仅仅是为了兼容旧版本而保留。唯一的作用就是保证构造map时初始容量不小于concurrencyLevel。
源码122行:
Also, for compatibility with previous
versions of this class, constructors may optionally specify an
expected {@code concurrencyLevel} as an additional hint for
internal sizing.
源码482行:
Mainly: We
leave untouched but unused constructor arguments refering to
concurrencyLevel .……
……
1、重要属性:
1.1 Node:
- static class Node implements Map.Entry {
- final int hash;
- final K key;
- volatile V val;
- volatile Node next;
-
- Node(inthash, K key, V val, Node next) {
- this.hash = hash;
- this.key = key;
- this.val = val;
- this.next = next;
- }
-
- public final K getKey() { return key; }
- public final V getValue() { return val; }
-
- public final int hashCode() { returnkey.hashCode() ^ val.hashCode(); }
- public final String toString(){ returnkey + "=" + val; }
- public final V setValue(V value) {
- throw new UnsupportedOperationException();
- }
-
- public final boolean equals(Object o) {
- Object k, v, u; Map.Entry,?> e;
- return ((oinstanceof Map.Entry) &&
- (k = (e = (Map.Entry,?>)o).getKey()) != null &&
- (v = e.getValue()) != null &&
- (k == key || k.equals(key)) &&
- (v == (u = val) || v.equals(u)));
- }
-
-
-
-
- Node find(inth, Object k) {
- Node e = this;
- if (k != null) {
- do {
- K ek;
- if (e.hash == h &&
- ((ek = e.key) == k || (ek != null && k.equals(ek))))
- returne;
- } while ((e = e.next) != null);
- }
- returnnull;
- }
- }
1.2 TreeNode
-
-
- static final class TreeNode extends Node {
- TreeNode parent;
- TreeNode left;
- TreeNode right;
- TreeNode prev;
- boolean red;
-
- TreeNode(inthash, K key, V val, Node next,
- TreeNode parent) {
- super(hash, key, val, next);
- this.parent = parent;
- }
-
- Node find(inth, Object k) {
- return findTreeNode(h, k, null);
- }
-
-
-
-
-
- final TreeNode findTreeNode(int h, Object k, Class> kc) {
- if (k != null) {
- TreeNode p = this;
- do {
- intph, dir; K pk; TreeNode q;
- TreeNode pl = p.left, pr = p.right;
- if ((ph = p.hash) > h)
- p = pl;
- elseif (ph < h)
- p = pr;
- elseif ((pk = p.key) == k || (pk != null && k.equals(pk)))
- returnp;
- elseif (pl == null)
- p = pr;
- elseif (pr == null)
- p = pl;
- elseif ((kc != null ||
- (kc = comparableClassFor(k)) != null) &&
- (dir = compareComparables(kc, k, pk)) != 0)
- p = (dir < 0) ? pl : pr;
- elseif ((q = pr.findTreeNode(h, k, kc)) != null)
- returnq;
- else
- p = pl;
- } while (p != null);
- }
- return null;
- }
- }
-
1.3 TreeBin
-
-
- TreeBin(TreeNode b) {
- super(TREEBIN, null, null, null);
- this.first = b;
- TreeNode r = null;
- for (TreeNode x = b, next; x != null; x = next) {
- next = (TreeNode)x.next;
- x.left = x.right = null;
- if (r == null) {
- x.parent = null;
- x.red = false;
- r = x;
- }
- else {
- K k = x.key;
- inth = x.hash;
- Class> kc = null;
- for (TreeNode p = r;;) {
- intdir, ph;
- K pk = p.key;
- if ((ph = p.hash) > h)
- dir = -1;
- elseif (ph < h)
- dir = 1;
- elseif ((kc == null &&
- (kc = comparableClassFor(k)) == null) ||
- (dir = compareComparables(kc, k, pk)) == 0)
- dir = tieBreakOrder(k, pk);
- TreeNode xp = p;
- if ((p = (dir <= 0) ? p.left : p.right) == null) {
- x.parent = xp;
- if (dir <= 0)
- xp.left = x;
- else
- xp.right = x;
- r = balanceInsertion(r, x);
- break;
- }
- }
- }
- }
- this.root = r;
- assert checkInvariants(root);
- }
1.4 treeifyBin
-
-
-
-
- private final void treeifyBin(Node[] tab, int index) {
- Node b; intn, sc;
- if (tab != null) {
- if ((n = tab.length) < MIN_TREEIFY_CAPACITY)
- tryPresize(n << 1);
- else if ((b = tabAt(tab, index)) != null && b.hash >= 0) {
- synchronized (b) {
- if (tabAt(tab, index) == b) {
- TreeNode hd = null, tl = null;
- for (Node e = b; e != null; e = e.next) {
- TreeNode p =
- new TreeNode(e.hash, e.key, e.val,
- null, null);
- if ((p.prev = tl) == null)
- hd = p;
- else
- tl.next = p;
- tl = p;
- }
- setTabAt(tab, index, new TreeBin(hd));
- }
- }
- }
- }
- }
1.5 ForwardingNode
-
-
- static final class ForwardingNode extends Node {
- final Node[] nextTable;
- ForwardingNode(Node[] tab) {
- super(MOVED, null, null, null);
- this.nextTable = tab;
- }
-
- Node find(int h, Object k) {
-
- outer: for (Node[] tab = nextTable;;) {
- Node e; intn;
- if (k == null || tab == null || (n = tab.length) == 0 ||
- (e = tabAt(tab, (n - 1) & h)) == null)
- returnnull;
- for (;;) {
- int eh; K ek;
- if ((eh = e.hash) == h &&
- ((ek = e.key) == k || (ek != null && k.equals(ek))))
- returne;
- if (eh < 0) {
- if (e instanceof ForwardingNode) {
- tab = ((ForwardingNode)e).nextTable;
- continue outer;
- }
- else
- return e.find(h, k);
- }
- if ((e = e.next) == null)
- return null;
- }
- }
- }
- }
1.6 3个原子操作(调用频率很高)
- @SuppressWarnings("unchecked")
- static final Node tabAt(Node[] tab, int i) {
- return (Node)U.getObjectVolatile(tab, ((long)i << ASHIFT) + ABASE);
- }
-
- static final boolean casTabAt(Node[] tab, int i,
- Node c, Node v) {
- return U.compareAndSwapObject(tab, ((long)i << ASHIFT) + ABASE, c, v);
- }
-
- static final void setTabAt(Node[] tab, int i, Node v) {
- U.putObjectVolatile(tab, ((long)i << ASHIFT) + ABASE, v);
- }
1.7 Unsafe
-
-
- private static final sun.misc.Unsafe U;
- private static final long SIZECTL;
- private static final long TRANSFERINDEX;
- private static final long BASECOUNT;
- private static final long CELLSBUSY;
- private static final long CELLVALUE;
- private static final long ABASE;
- private static final int ASHIFT;
-
- static {
- try {
- U = sun.misc.Unsafe.getUnsafe();
- Class> k = ConcurrentHashMap.class;
- SIZECTL = U.objectFieldOffset (k.getDeclaredField("sizeCtl"));
- TRANSFERINDEX=U.objectFieldOffset(k.getDeclaredField("transferIndex"));
- BASECOUNT = U.objectFieldOffset (k.getDeclaredField("baseCount"));
- CELLSBUSY = U.objectFieldOffset (k.getDeclaredField("cellsBusy"));
- Class> ck = CounterCell.class;
- CELLVALUE = U.objectFieldOffset (ck.getDeclaredField("value"));
- Class> ak = Node[].class;
- ABASE = U.arrayBaseOffset(ak);
- intscale = U.arrayIndexScale(ak);
- if ((scale & (scale - 1)) != 0)
- thrownew Error("data type scale not a power of two");
- ASHIFT = 31 - Integer.numberOfLeadingZeros(scale);
- } catch (Exception e) {
- thrownew Error(e);
- }
- }
1.8 扩容相关
tryPresize
在putAll以及treeifyBin中调用
- private final void tryPresize(int size) {
-
- int c = (size >= (MAXIMUM_CAPACITY >>> 1)) ? MAXIMUM_CAPACITY :
- tableSizeFor(size + (size >>> 1) + 1);
- int sc;
- while ((sc = sizeCtl) >= 0) {
- Node[] tab = table; int n;
- if(tab == null || (n = tab.length) == 0) {
- n = (sc > c) ? sc : c;
-
- if (U.compareAndSwapInt(this, SIZECTL, sc, -1)) {
- try {
- if (table == tab) {
- @SuppressWarnings("unchecked")
- Node[] nt = (Node[])new Node,?>[n];
- table = nt;
- sc = n - (n >>> 2);
- }
- } finally {
- sizeCtl = sc;
- }
- }
- }
- else if (c <= sc || n >= MAXIMUM_CAPACITY)
- break;
- else if (tab == table) {
- int rs = resizeStamp(n);
- if (sc < 0) {
- Node[] nt;
- 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);
- }
- }
- }
- private static final int tableSizeFor(int c){
- int n = c - 1;
- n |= n >>> 1;
- n |= n >>> 2;
- n |= n >>> 4;
- n |= n >>> 8;
- n |= n >>> 16;
- return (n < 0) ? 1 : (n >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1;
- }
-
-
-
-
- static final int resizeStamp(int n) {
- return Integer.numberOfLeadingZeros(n) | (1 << (RESIZE_STAMP_BITS - 1));
- }
-
ConcurrentHashMap无锁多线程扩容,减少扩容时的时间消耗。
transfer扩容操作
:单线程构建两倍容量的nextTable;允许多线程复制原table元素到nextTable。
- 为每个内核均分任务,并保证其不小于16;
- 若nextTab为null,则初始化其为原table的2倍;
- 死循环遍历,直到finishing。
- 节点为空,则插入ForwardingNode;
- 链表节点(fh>=0),分别插入nextTable的i和i+n的位置;【逆序链表??】
- TreeBin节点(fh<0),判断是否需要untreefi,分别插入nextTable的i和i+n的位置;【逆序树??】
- finishing时,nextTab赋给table,更新sizeCtl为新容量的0.75倍 ,完成扩容。
以上说的都是单线程,多线程又是如何实现的呢?
遍历到ForwardingNode节点((fh = f.hash) == MOVED),说明此节点被处理过了,直接跳过。这是控制并发扩容的核心
。
由于给节点上了锁,只允许当前线程完成此节点的操作,处理完毕后,将对应值设为ForwardingNode(fwd),其他线程看到forward,直接向后遍历。如此便完成了多线程的复制工作,也解决了线程安全问题。
private transient volatile Node[] nextTable; //仅仅在扩容使用,并且此时非空
-
-
- private final void transfer(Node[] tab, Node[] nextTab) {
- int n = tab.length, stride;
-
- if ((stride = (NCPU > 1) ? (n >>> 3) / NCPU : n) < MIN_TRANSFER_STRIDE)
- stride = MIN_TRANSFER_STRIDE;
- if (nextTab == null) {
- try {
- @SuppressWarnings("unchecked")
- Node[] nt = (Node[])new Node,?>[n << 1];
- nextTab = nt;
- } catch (Throwable ex) {
- sizeCtl = Integer.MAX_VALUE;
- return;
- }
- nextTable = nextTab;
- transferIndex = n;
- }
- int nextn = nextTab.length;
-
- ForwardingNode fwd= new ForwardingNode(nextTab);
- boolean advance= true;
- boolean finishing = false;
- for (int i = 0, bound = 0;;) {
- Node f; int fh;
- while (advance) {
- int nextIndex, nextBound;
- if (--i >= bound || finishing)
- advance = false;
- else if ((nextIndex = transferIndex) <= 0) {
- i = -1;
- advance = false;
- }
- else if (U.compareAndSwapInt
- (this, TRANSFERINDEX, nextIndex,
- nextBound = (nextIndex > stride ?
- nextIndex - stride : 0))) {
- bound = nextBound;
- i = nextIndex - 1;
- advance = false;
- }
- }
- if (i < 0 || i >= n || i + n >= nextn) {
- int sc;
- if (finishing) {
- nextTable = null;
- table = nextTab;
- sizeCtl = (n << 1) - (n >>> 1);
- return;
- }
- if (U.compareAndSwapInt(this, SIZECTL, sc = sizeCtl, sc - 1)) {
- if ((sc - 2) != resizeStamp(n) << RESIZE_STAMP_SHIFT)
- return;
- finishing = advance = true;
- i = n;
- }
- }
- else if ((f = tabAt(tab, i)) == null)
- advance = casTabAt(tab, i, null, fwd);
-
- else if ((fh = f.hash) == MOVED)
- advance = true;
- else {
- synchronized (f) {
- if (tabAt(tab, i) == f) {
- Node ln, hn;
- if (fh >= 0) {
- int runBit = fh & n;
- Node lastRun = f;
- for (Node 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 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(ph, pk, pv, ln);
- else
- hn = new Node(ph, pk, pv, hn);
- }
- setTabAt(nextTab, i, ln);
- setTabAt(nextTab, i + n, hn);
-
- setTabAt(tab, i, fwd);
-
- advance = true;
- }
- else if (f instanceof TreeBin) {
- TreeBin t = (TreeBin)f;
- TreeNode lo = null, loTail = null;
- TreeNode hi = null, hiTail = null;
-
- int lc = 0, hc = 0;
- for (Node e = t.first; e != null; e = e.next) {
- int h = e.hash;
- TreeNode p = new TreeNode
- (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(lo) : t;
- hn = (hc <= UNTREEIFY_THRESHOLD) ? untreeify(hi) :
- (lc != 0) ? new TreeBin(hi) : t;
- setTabAt(nextTab, i, ln);
- setTabAt(nextTab, i + n, hn);
- setTabAt(tab, i, fwd);
- advance = true;
- }
- }
- }
- }
- }
- }
-
-
- final Node[] helpTransfer(Node[] tab, Node f) {
- Node[] nextTab; intsc;
- if (tab != null && (finstanceof ForwardingNode) &&
- (nextTab = ((ForwardingNode)f).nextTable) != null) {
- intrs = resizeStamp(tab.length);
- while (nextTab == nextTable && table == tab &&
- (sc = sizeCtl) < 0) {
- if ((sc >>> RESIZE_STAMP_SHIFT) != rs || sc == rs + 1 ||
- sc == rs + MAX_RESIZERS || transferIndex <= 0)
- break;
- if (U.compareAndSwapInt(this, SIZECTL, sc, sc + 1)) {
- transfer(tab, nextTab);
- break;
- }
- }
- return nextTab;
- }
- return table;
- }
2、 put相关:
理一下put的流程:
①
判空:null直接抛空指针异常;
②
hash:计算h=key.hashcode;调用spread计算hash=
(
h
^(
h
>>>
16
))&
HASH_BITS;
③
遍历table
- 若table为空,则初始化,仅设置相关参数;
- @@@计算当前key存放位置,即table的下标i=(n - 1) & hash;
- 若待存放位置为null,casTabAt无锁插入;
- 若是forwarding nodes(检测到正在扩容),则helpTransfer(帮助其扩容);
- else(待插入位置非空且不是forward节点,即碰撞了),将头节点上锁(保证了线程安全):区分链表节点和树节点,分别插入(遇到hash值与key值都与新节点一致的情况,只需要更新value值即可。否则依次向后遍历,直到链表尾插入这个结点);
- 若链表长度>8,则treeifyBin转树(Note:若length<64,直接tryPresize,两倍table.length;不转树)。
④
addCount(1L, binCount)。
Note:
1、put操作共计两次hash操作,再利用“与&”操作计算Node的存放位置。
2、ConcurrentHashMap不允许key或value为null。
3、
addCount(longx,intcheck)方法:
①利用CAS快速更新baseCount的值;
②check>=0.则检验是否需要扩容;
if sizeCtl<0(正在进行初始化或扩容操作)【nexttable null等情况break;如果有线程正在扩容,则协助扩容】;
else if
仅当前线程在扩容,调用协助扩容函数,注其参数nextTable为null。
public V put(K key, V value) {
return putVal(key, value, false);
}
- final V "background-color: rgb(255, 255, 51);">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[] tab = table;;) {
- Node f; int n, i, fh;
- if (tab == null || (n = tab.length) == 0)
- tab = initTable();
- else if ((f = tabAt(tab, i = (n - 1) & hash)) == null) {
- if (casTabAt(tab, i, null,
- new Node(hash, key, value, null)))
- break;
- }
- 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 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 pred = e;
- if ((e = e.next) == null) {
- pred.next = new Node(hash, key, value, null);
- break;
- }
- }
- }
- else if (f instanceof TreeBin) {
- Node p;
- binCount = 2;
- if ((p = ((TreeBin)f).putTreeVal(hash, key,value)) != null) {
- oldVal = p.val;
- if (!onlyIfAbsent)
- p.val = value;
- }
- }
- }
- }
- if (binCount != 0) {
- if (binCount >= TREEIFY_THRESHOLD)
- treeifyBin(tab, i);
- if (oldVal != null)
- return oldVal;
- break;
- }
- }
- }
- addCount(1L, binCount);
- return null;
- }
-
- private final Node[] "background-color: rgb(255, 255, 51);">initTable() {
- Node[] tab; intsc;
- while ((tab = table) == null || tab.length == 0) {
- if ((sc = sizeCtl) < 0)
- Thread.yield();
-
- elseif (U.compareAndSwapInt(this, SIZECTL, sc, -1)) {
- try {
- if ((tab = table) == null || tab.length == 0) {
- intn = (sc > 0) ? sc : DEFAULT_CAPACITY;
- @SuppressWarnings("unchecked")
- Node[] nt = (Node[])new Node,?>[n];
- table = tab = nt;
- sc = n - (n >>> 2);
- }
- } finally {
- sizeCtl = sc;
- }
- break;
- }
- }
- return tab;
- }
3、 get、contains相关
- public V "background-color: rgb(255, 255, 51);">get(Object key) {
- Node[] tab; Node e, p; intn, eh; K ek;
- inth = 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)))
- returne.val;
- }
- elseif (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))))
- returne.val;
- }
- }
- return null;
- }
- public boolean containsKey(Object key) {return get(key) != null;}
- public boolean containsValue(Object value) {}
理一下get的流程:
①spread计算hash值;
②table不为空;
③tabAt(i)处桶位不为空;
④check first,是则返回当前Node的value;否则分别根据树、链表查询。
4、 Size相关:
由于ConcurrentHashMap在统计size时
可能正被
多个线程操作,而我们又不可能让他停下来让我们计算,所以只能计量一个估计值。
计数辅助:
// Table of counter cells. When non-null, size is a power of 2
private transient volatile CounterCell[] counterCells;
|
@sun.misc.Contended static final class CounterCell {
volatile long value;
CounterCell(long x) { value = x; }
}
|
final long sumCount(){
CounterCell as[] = counterCells;
long sum = baseCount;
if(as != null){
for(int i = 0; i < as.length; i++){
CounterCell a;
if((a = as[i]) != null)
sum += a.value;
}
}
return sum;
}
|
private final void fullAddCount(long x, boolean wasUncontended) {}
|
public int size() { // 旧版本方法,和推荐的mappingCount返回的值基本无区别
longn = sumCount();
return ((n < 0L) ? 0 :
(n > (long)Integer.MAX_VALUE) ? Integer.MAX_VALUE :
(int)n);
}
|
// 返回Mappings中的元素个数,官方建议用来替代size。此方法返回的是一个估计值;如果sumCount时有线程插入或删除,实际数量是和mappingCount不同的。since 1.8
public long mappingCount() {
longn = sumCount();
return (n < 0L) ? 0L : n; // ignore transient negative values
}
|
private
transient
volatile
long
baseCount
;
//ConcurrentHashMap中元素个数,基于CAS无锁更新,但返回的不一定是当前Map的真实元素个数。
|
5、remove、clear相关:
- public void clear() {
- long delta = 0L;
- inti = 0;
- Node[] tab = table;
- while (tab != null && i < tab.length) {
- intfh;
- Node f = tabAt(tab, i);
- if (f == null)
- ++i;
- else if ((fh = f.hash) == MOVED) {
-
- tab = helpTransfer(tab, f);
- i = 0;
- }
- else{
- synchronized (f) {
- if (tabAt(tab, i) == f) {
- Node p = (fh >= 0 ? f :
- (finstanceof TreeBin) ?
- ((TreeBin)f).first : null);
- while (p != null) {
- --delta;
- p = p.next;
- }
- setTabAt(tab, i++, null);
- }
- }
- }
- }
- if (delta != 0L)
- addCount(delta, -1);
- }
- public V remove(Object key) {
- return replaceNode(key, null, null);
- }
- public boolean remove(Object key, Object value) {
- if (key == null)
- thrownew NullPointerException();
- returnvalue != null && replaceNode(key, null, value) != null;
- }
-
- final V replaceNode(Object key, V value, Object cv) {
- inthash = spread(key.hashCode());
- for (Node[] tab = table;;) {
- Node f; intn, i, fh;
- if (tab == null || (n = tab.length) == 0 ||
- (f = tabAt(tab, i = (n - 1) & hash)) == null)
- break;
- elseif ((fh = f.hash) == MOVED)
- tab = helpTransfer(tab, f);
- else {
- V oldVal = null;
- booleanvalidated = false;
- synchronized (f) {
- if (tabAt(tab, i) == f) {
- if (fh >= 0) {
- validated = true;
-
- for (Node e = f, pred = null;;) {
- K ek;
- if (e.hash == hash &&((ek = e.key) == key ||
- (ek != null && key.equals(ek)))){
- V ev = e.val;
-
- if (cv == null || cv == ev ||
- (ev != null && cv.equals(ev))) {
- oldVal = ev;
- if (value != null)
- e.val = value;
- elseif (pred != null)
- pred.next = e.next;
- else
- setTabAt(tab, i, e.next);
- }
- break;
- }
- pred = e;
- if ((e = e.next) == null)
- break;
- }
- }
- elseif (finstanceof TreeBin) {
- validated = true;
- TreeBin t = (TreeBin)f;
- TreeNode r, p;
- if ((r = t.root) != null &&
- (p = r.findTreeNode(hash, key, null)) != null) {
- V pv = p.val;
- if (cv == null || cv == pv ||
- (pv != null && cv.equals(pv))) {
- oldVal = pv;
- if (value != null)
- p.val = value;
- elseif (t.removeTreeNode(p))
- setTabAt(tab, i, untreeify(t.first));
- }
- }
- }
- }
- }
- if (validated) {
- if (oldVal != null) {
- if (value == null)
- addCount(-1L, -1);
- returnoldVal;
- }
- break;
- }
- }
- }
- return null;
- }
- public boolean replace(K key, V oldValue, V newValue) {}
6、其他函数:
public boolean isEmpty() {
return sumCount() <= 0L; // ignore transient negative values
}
参考资料:
http://ifeve.com/concurrenthashmap/
http://ifeve.com/java-concurrent-hashmap-2/
、、、、、、、、、
http://ashkrit.blogspot.com/2014/12/what-is-new-in-java8-concurrenthashmap.html
http://blog.csdn.net/u010723709/article/details/48007881
http://yucchi.jp/blog/?p=2048
http://blog.csdn.net/q291611265/article/details/47985145
、、、、、、、、、、
SynchronizedMap:http://blog.sina.com.cn/s/blog_5157093c0100hm3y.html
http://blog.csdn.net/yangfanend/article/details/7165742
http://blog.csdn.net/xuefeng0707/article/details/40797085
1
2
3
4
5
6
7
8
9
10
11 |
ArrayList源码分析(jdk1.8):http://blog.csdn.net/u010887744/article/details/49496093
HashMap源码分析(jdk1.8):http://write.blog.csdn.net/postedit/50346257
ConcurrentHashMap源码分析--Java8:http://blog.csdn.net/u010887744/article/details/50637030
每篇文章都包含 有道云笔记地址,可直接保存。
在线查阅JDK源码:
JDK8:https://github.com/zxiaofan/JDK1.8-Src
JDK7:https://github.com/zxiaofan/JDK_Src_1.7
史上最全Java集合关系图:http://blog.csdn.net/u010887744/article/details/50575735
|
来自CODE的代码片
SourceCode
1
2
3
4
5
6
7
8
9
10 |
转载请注明出处,谢谢。
【 CSDN 】:csdn.zxiaofan.cn
【GitHub】:github.zxiaofan.cn
域名备案中,上述网址极不稳定,GitHub请直接访问【github.com/zxiaofan】
如有任何问题,欢迎留言。祝君好运!
Life is all about choices!
将来的你一定会感激现在拼命的自己!
|
来自CODE的代码片
txt