ConcurrentHashMap

1,ConcurrentHashMap 数据结构

ConcurrentHashMap 在JDK 1.8 之后数据结构和HashMap 数据结构非常相似,都是数组 + 链表/红黑树 的形式

 

2, ConcurrentHashMap 线程安全

ConcurrentHashMap 是线程安全的,其内部是通过什么实现了安全机制呢?

CAS无锁机制 + syncronized 

 

ConcurrentHashMap 的put 流程

   public V put(K key, V value) {
// 调用putVal 插入元素
return putVal(key, value, false); } final V putVal(K key, V value, boolean onlyIfAbsent) {
if (key == null || value == null) throw new NullPointerException();
// 获取key的hash值
int hash = spread(key.hashCode()); int binCount = 0; for (Node<K,V>[] tab = table;;) { Node<K,V> f; int n, i, fh;
// 当tab 为空的时候,要初始化数组
if (tab == null || (n = tab.length) == 0) tab = initTable();
// 完成初始化之后,继续循环,直到break

// 情况1: 根据hash 以及table数组的长度,算出这个key对应的下标,没有冲突,直接插入到数组中
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 }
// 情况2:有线程正在扩容,也可以协助一块扩容
else if ((fh = f.hash) == MOVED) tab = helpTransfer(tab, f);
// 情况3:正常的有冲突,放到链表上,达到红黑树的要求,就转变成红黑树
else {
V oldVal
= null;
// syncronized 保证线程安全
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; }
// 遍历链表,通过e = e.next一直到下一个节点为null 的时候插入 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; } } } } if (binCount != 0) { if (binCount >= TREEIFY_THRESHOLD) treeifyBin(tab, i); if (oldVal != null) return oldVal; break; } } }
addCount(
1L, binCount); return null; }

 

初始化 数组

private final Node<K,V>[] initTable() {
        Node<K,V>[] tab; int sc;
        while ((tab = table) == null || tab.length == 0) {
// sizeCtl 初始化就是0,当有线程在执行初始化(也就是sizeCtl是-1的时候),就会做出让步yield()
if ((sc = sizeCtl) < 0) Thread.yield(); // lost initialization race; just spin
// 通过CAS 无锁机制(当内存中值和预计要改变的值相等,则改为-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;
//初始化tab 的长度为16,sc 则为12,相当于一个阀值一样,concurrentHashMap 里面的元素个数超过12 就需要扩容 sc
= n - (n >>> 2); } } finally { sizeCtl = sc; } break; } } return tab; }

 

posted @ 2019-09-24 09:23  Chris,Cai  阅读(208)  评论(0编辑  收藏  举报