并发编程(1)-java中的6中线程状态
并发编程(2)-怎么中断线程?
并发编程(3)-synchronized的实现原理
并发编程(4)-深入理解volatile关键字
并发编程(5)-ReentrantLock源码分析
并发编程(6)-Condition源码分析
并发编程(7)-juc阻塞队列介绍
并发编程(8)-什么是异步责任链
并发编程(9)-Semaphore介绍和源码分析
并发编程(10)-CyclicBarrier的使用及其源码分析
并发编程(11)-forkJoin基本使用
一、为什么要用ConcurrentHashMap
HashMap -> 非线程安全的
HashTable -> synchronized(偏向锁、轻量级锁(CAS))粒度大,性能低
二、ConcurrentHashMap1.8的提供的api
用了ConcurrentHashMap1.8 不代表怎么操作都是线程安全的
ConcurrentHashMap<String, String> hashMap = new ConcurrentHashMap<>();
String name = hashMap.get("name");
if (name == null) {
// 这里希望会有线程执行多次
hashMap.put("name", "kanping");
}
1.8提供的这些方法可以保证线程安全
- computeIfAbsent :如果不存在,则执行。如果存在,则不进行操作。
ConcurrentHashMap<String, String> hashMap = new ConcurrentHashMap<>();
hashMap.computeIfAbsent("name", e ->"kangping");
System.out.println(hashMap);
hashMap.computeIfAbsent("name", e -> "zhoutao");
System.out.println(hashMap);
结果:
- computeIfPresent :如果存在,则执行。如果不存在,则不进行操作。
ConcurrentHashMap<String, String> hashMap = new ConcurrentHashMap<>();
hashMap.computeIfAbsent("name", e ->"kangping");
System.out.println(hashMap);
hashMap.computeIfAbsent("name", e -> "zhoutao");
System.out.println(hashMap);
结果:
- compute:computeIfAbsent和computeIfPresent两者的结合,key不存在,执行。存在,则覆盖
ConcurrentHashMap<String, String> concurrentHashMap1 = new ConcurrentHashMap<>();
concurrentHashMap1.compute("name", (e,e2) -> "kangping");
System.out.println(concurrentHashMap1);
concurrentHashMap1.compute("name", (e,e2) ->"zhoutao");
System.out.println(concurrentHashMap1);
结果:
三、源码分析
put()方法 :插入一个元素
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;
// 如果table 为空,则初始化
if (tab == null || (n = tab.length) == 0)
tab = initTable();
else if ((f = tabAt(tab, i = (n - 1) & hash)) == null) {
// 如果不为空,数组下表的位置是空,则通过case操作,插入数据
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;
// 相同的key,直接覆盖
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;
// hash值相同,key值不相同,则在链表末尾追加节点
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) {
// binCount 是hash冲突下的结点数量,大于等于8,进行扩容操作
if (binCount >= TREEIFY_THRESHOLD)
treeifyBin(tab, i);
if (oldVal != null)
return oldVal;
break;
}
}
}
// 对集合数量计数
addCount(1L, binCount);
return null;
}
initTable():初始化数据结构,这里是一个node数组
private final Node<K,V>[] initTable() {
Node<K,V>[] tab; int sc;
while ((tab = table) == null || tab.length == 0) {
// sizeCtl < 0 代表已经有线程在初始化了,直接放弃cpu时间片
if ((sc = sizeCtl) < 0)
Thread.yield(); // lost initialization race; just spin
// SIZECTL = -1 修改成功,代表抢到了锁
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); // 扩容的阈值,加入初始容量是16 则这个值是12 (3/4)
}
} finally {
sizeCtl = sc;
}
break;
}
}
return tab;
}
treeifyBin() :扩容或者是进行红黑树的转化
会根据阈值来判断,是转化为红黑树还是扩容
private final void treeifyBin(Node<K,V>[] tab, int index) {
Node<K,V> b; int n, sc;
if (tab != null) {
// 如果数组长度小于64 ,则扩容
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<K,V> hd = null, tl = null;
for (Node<K,V> e = b; e != null; e = e.next) {
TreeNode<K,V> p =
new TreeNode<K,V>(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<K,V>(hd));
}
}
}
}
}
tryPresize():扩容方法
private final void tryPresize(int size) {
// 数组大小如果,如果大于最大的一半。则直接设置最大容量,否则设置最近为 2指数次幂最接近的值
int c = (size >= (MAXIMUM_CAPACITY >>> 1)) ? MAXIMUM_CAPACITY :
tableSizeFor(size + (size >>> 1) + 1);
int sc;
while ((sc = sizeCtl) >= 0) {
Node<K,V>[] 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<K,V>[] nt = (Node<K,V>[])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<K,V>[] nt;
// 表示扩容结束
if ((sc >>> RESIZE_STAMP_SHIFT) != rs || sc == rs + 1 ||
sc == rs + MAX_RESIZERS || (nt = nextTable) == null ||
transferIndex <= 0)
break;
// 增加一个线程,扩容戳低位加1
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);
}
}
}
tryPresize 是支持多个线程并发扩容的,有多少个线程在扩容,我们需要记录这个数字。
resizeStamp (): 扩容戳,保证当前扩容范围的唯一性
static final int resizeStamp(int n) {
return Integer.numberOfLeadingZeros(n) | (1 << (RESIZE_STAMP_BITS - 1));
}
n = 16:
0000 0000 0000 0000 0000 0000 0001 0000 -> 27位
0000 0000 0000 0000 1000 0000 0001 1011
resizeStamp返回的数: 1000 0000 0001 1011 0000 0000 0000 0000
rs << RESIZE_STAMP_SHIFT) + 2 ,二进制左移16位+2
1000 0000 0001 1011 0000 0000 0000 0010 ->表示当前有一个线程来扩容。 (为什么不是+1.好像是为了防止什么冲突。但是可以认为第一个线程是+2,后面来的线程都是+1)
高位16表示当前的扩容标记, 保证唯一性.
低16位表示当前扩容的线程数量.
transfer() : 迁移方法
private final void transfer(Node<K,V>[] tab, Node<K,V>[] nextTab) {
int n = tab.length, stride;
// 计算每个线程处理的数据的区间大小,最小是16。
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;
//用来表示已经迁移完的状态,也就是说,如果某个old数组的节点完成了迁移,则需要更改成fwd。
ForwardingNode<K,V> fwd = new ForwardingNode<K,V>(nextTab);
boolean advance = true;
boolean finishing = false; // to ensure sweep before committing nextTab
for (int i = 0, bound = 0;;) {
Node<K,V> 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;
}
}
//假设数组长度是32,
//第一次 [16(nextBound),31(i)]
//第二次 [0,15]
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; // recheck before commit
}
}
//说明当前数组位置为空。
//直接改成fwd -> 表示迁移完成
else if ((f = tabAt(tab, i)) == null)
advance = casTabAt(tab, i, null, fwd);
// 表示已经处理过了
else if ((fh = f.hash) == MOVED)
advance = true; // already processed
else {
//加锁->针对当前要去迁移的节点。
//保证迁移过程中,其他线程调用put()方法时,必须要等待。
synchronized (f) {
if (tabAt(tab, i) == f) {
Node<K,V> ln, hn;
// 链表的操作
if (fh >= 0) {
int runBit = fh & n;
Node<K,V> lastRun = f;
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);
}
setTabAt(nextTab, i, ln);
setTabAt(nextTab, i + n, hn);
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;
}
}
}
}
}
}
当数组扩容之后,会存在两种情况
数组位置不会发生变化数组位置会发生变化
统计元素个数
private transient volatile long baseCount;
private transient volatile CounterCell[] counterCells;
- 如果竞争不激烈的情况下,直接用cas( baseCount+1)
- 如果竞争激烈的情况下,采用数组的方式来进行计数。