什么是CHM ?
1、CHM 全称:ConcurrentHashMap 是J.U.C工具包中所提供的,显然是个map集合,而且是个线程安全的HashMap,既然是线程安全的那么显然下并发场景下用的还是比较频繁的。
2、CHM作用和HashMap差不太多,也可以说是一个线程安全的HashMap
3、使用和普通的Map是一致的,包含put,get 方法等
ConcurrentHashMap chmMap = new ConcurrentHashMap();
chmMap.put("key","value");
chmMap.get("key");
CHM的发展
这里为什么说下它的发展呢,是因为在jdk1.7和jdk1.8这2个版本下发生了一些比较大的变化(即对它进行的优化升级)
jdk1.7版本的主要内容:jdk1.7在线程安全方面主要利用到了分段锁(segment),简单的说一个CHM是由N(初始化16)个segment组成的,这样的话就通过在每个segment端上加锁来控制线程安全的。
如下图:
jdk1.8 针对jdk1.7做了些改进 主要有如下:
1、取消了segement分段锁这部分
2、由原来的数字+单向链表 改为 数组+单向链表(或红黑树)
原因: 1、去掉segment的分段锁,使得锁的范围更小了,减少了阻塞的概率,提升锁的效率。
2、数组+链表,缺点:单向链表的时间复杂度为0(n),如果同一个节点hash碰撞过多的话,那么这个节点的单向链表的长度就很可能成为整个map查询的瓶颈了。因此优化了当单向链表的长度增加到了8(默认),那么就会由原来的链表转为红黑树,红黑树的查询效率比链表要高很多0(logn),利用了二分查找等机制,加速了查找速度。
如下图:
CHM的原理浅析
初始化
// 初始化数组
private final Node<K,V>[] initTable() {
Node<K,V>[] tab; int sc;
// 循环存在多线程竞争的情况下
while ((tab = table) == null || tab.length == 0) {
if ((sc = sizeCtl) < 0) // 以及被其他线程抢到了,开始初始化了
Thread.yield(); // lost initialization race; just spin
else if (U.compareAndSwapInt(this, SIZECTL, sc, -1)) {
try {
// cas原子操作,标记已经在初始化了,与第一个if相对应
if ((tab = table) == null || tab.length == 0) {
// 默认初始值16 。
// private static final int DEFAULT_CAPACITY = 16;
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); //扩容因子,下次需要扩容的大小(0.75)
}
} finally {
sizeCtl = sc;
}
break;
}
}
return tab;
}
/** Implementation for put and putIfAbsent */
final V putVal(K key, V value, boolean onlyIfAbsent) {
//键不能为空,否则报错
if (key == null || value == null) throw new NullPointerException();
//hash
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) {
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;
}
}
}
}
// static final int TREEIFY_THRESHOLD = 8;
if (binCount != 0) {
// 如果节点数,大于初始值默认8),那么转成红黑树
if (binCount >= TREEIFY_THRESHOLD)
treeifyBin(tab, i);
if (oldVal != null)
return oldVal;
break;
}
}
}
addCount(1L, binCount);
return null;
}
============
Class<?> ak = Node[].class;
ABASE = U.arrayBaseOffset(ak);
int scale = U.arrayIndexScale(ak);
if ((scale & (scale - 1)) != 0)
throw new Error("data type scale not a power of two");
ASHIFT = 31 - Integer.numberOfLeadingZeros(scale);
=============
@SuppressWarnings("unchecked")
static final <K,V> Node<K,V> tabAt(Node<K,V>[] tab, int i) {
// 此方法 是通过获取offset的偏移量 如上代码,实际等价于tab[i],那么为什么不这么取值?
return (Node<K,V>)U.getObjectVolatile(tab, ((long)i << ASHIFT) + ABASE);
}
为什么通过tabAt()单独的去获取值呢??不知直接用tab[i]更家直接的获取值呢?
原因: 看代码上getObjectVolatile 虽然有volatile关键字,但是我们都知道,因为对 volatile 写操作 happen-before 于 volatile 读操作,
因此其他线程对 table 的修改均对 get 读取可见的,由此可见直接tab[i] 不一定能获取的最新的值。
虽然 table 数组本身是增加了 volatile 属性,但是“volatile 的数组只针对数组的引用具有volatile 的语义,而不是它的元素”。所以就直接用内存上的偏移量来获取值。
个数计算
api 方法 - > chmMap.size();
这个计算计算个数由于涉及到多线程,那么单纯的计算个数是可能不准确的,因此这边利用的分而治之的算法方式,来获取最后的个数
/**
* 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
*/
private final void addCount(long x, int check) {
CounterCell[] as; long b, s;
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();
}
if (check >= 0) {
Node<K,V>[] tab, nt; int n, sc;
while (s >= (long)(sc = sizeCtl) && (tab = table) != null &&
(n = tab.length) < MAXIMUM_CAPACITY) {
int rs = resizeStamp(n);
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();
}
}
}
// 求计算个数的table初始化 默认大小为2,后面也可以扩容
else if (cellsBusy == 0 && counterCells == as &&
U.compareAndSwapInt(this, CELLSBUSY, 0, 1)) {
boolean init = false;
try {
// Initialize table
if (counterCells == as) {
CounterCell[] rs = new CounterCell[2];
rs[h & 1] = new CounterCell(x);
counterCells = rs;
init = true;
}
} finally {
cellsBusy = 0;
}
扩容
数据迁移