是HashMap的并发版本
原子复合操作
实现了接口ConcurrentMap
以下是其中方法
//条件更新,
如果Map中没有key,设置key为value,
//返回原来key对应的值,如果没有,返回null
V putIfAbsent(K key, V value);
//条件删除,
如果Map中有key,且对应的值为value,则删除,
如果删除了,返回true,否则false
boolean remove(Object key, Object value);
//条件替换,
如果Map中有key,且对应的值为oldValue,则替换为newValue,
如果替换了,返回ture,否则false
boolean replace(K key, V oldValue, V newValue);
//条件替换,
如果Map中有key,则替换值为value,返回原来key对应的值,
如果原来没有,返回null
V replace(K key, V value);
ConcurrentHashMap如何做到高并发的?
7里面
- 分段锁
- 读并行
采用分段锁技术,将数据分为多个段(默认16个),而每个段有一个独立的锁
分多少段,可以通过构造方法进行设置,如下所示:
public ConcurrentHashMap(int initialCapacity, float loadFactor, int concurrencyLevel)
concurrencyLevel表示估计的并行更新的线程个数,ConcurrentHashMap会将该数转换为2的整数次幂,比如14转换为16,25转换为32。
在对每个段的数据进行读写时,
也不是简单的使用锁进行同步,内部使用了CAS、对一些写采用原子方式,
实现的效果是,对于写操作,需要获取锁,不能并行,
但是读操作可以并行, 读写可以并行 (循环,不一定能读到最新的,弱一致性)
8更进一步
bucket数组是一样的
/**
* The array of bins. Lazily initialized upon first insertion.
* Size is always a power of two. Accessed directly by iterators.
*/
transient volatile Node<K,V>[] table;
和1.8hashMap一样由链表或者红黑树组成, 这主要是为了安全, 怕恶意传来hash碰撞的key
static class Node<K,V> implements Map.Entry<K,V> {
//key 是final 不可变
final int hash;
final K key;
//可见性
volatile V val;
volatile Node<K,V> next;
.....
}
static final class TreeNode<K,V> extends Node<K,V> {
TreeNode<K,V> parent; // red-black tree links
TreeNode<K,V> left;
TreeNode<K,V> right;
TreeNode<K,V> prev; // needed to unlink next upon deletion
boolean red;
}
但是 分段锁不如就锁那个头结点 synchronized (f)
/** Implementation for put and putIfAbsent */
final V putVal(K key, V value, boolean onlyIfAbsent) {
//k v 都不能为null
if (key == null || value == null) throw new NullPointerException();
int hash = spread(key.hashCode());// 计算key 的hash值
int binCount = 0;
// 死循环 CAS 直到成功
for (Node<K,V>[] tab = table;;) {
Node<K,V> f; int n, i, fh;
// 第一次插入 初始化操作
if (tab == null || (n = tab.length) == 0)
tab = initTable();
// 这个位置f是空的 直接无锁放进去就好了
else if ((f = tabAt(tab, i = (n - 1) & hash)) == null) {
// CAS
if (casTabAt(tab, i, null, new Node<K,V>(hash, key, value, null)))
break;//失败就下一次循环
}
// 有其他线程在移动
else if ((fh = f.hash) == MOVED)
tab = helpTransfer(tab, f);// 协助扩容
else {
V oldVal = null;
// 注意 这里只锁了头结点!
// 注意 这里不用ReentrantLock了 因为性能已经优化 能减少内存
synchronized (f) {
//..... 细粒度的同步
// 从头开始遍历 一一比较key 覆盖或者插入
}
if (binCount != 0) {
// 太长了 树化
if (binCount >= TREEIFY_THRESHOLD)
treeifyBin(tab, i);
if (oldVal != null)
return oldVal;
break;
}
}
}
addCount(1L, binCount);
return null;
}
初始化代码:
// 正在初始化或扩容状态标记
// -1 表示一个 -n 表示 n-1个线程在扩容
private transient volatile int sizeCtl;
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 {
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);
}
} finally {
sizeCtl = sc;
}
break;
}
}
return tab;
}
1.50多个内部类 java并发精髓都在里面了
2.https://blog.csdn.net/elricboa/article/details/70199409
size return integer,mappingCount return long. No other difference