多线程之concurrenthashmap

多线程之concurrenthashmap

HashMap Recap

Screen Shot 2020-09-02 at 9.53.18 PM

链表超过最大长度(8),将链表改为红黑树再添加元素

Fail Fast

HashMap 中的 Iterator 迭代器是 fail-fast , 用迭代器遍历一个集合对象时,如果遍历过程中对集合对象的内容进行了修改(增加、删除、修改),则会抛出Concurrent Modification Exception。

迭代器在遍历时直接访问集合中的内容,并且在遍历过程中使用一个 modCount 变量。每当迭代器使用hashNext()/next()遍历下一个元素之前,都会检测modCount变量是否为expectedmodCount值,是的话就返回遍历;否则抛出异常,终止遍历。

ConcurrentHashMap

HashMap 非线程安全 (例如多线程场景,扩容 = resize + rehash, rehash会有并发问题),hashtable和Collections.synchronizedMap(hashMap), 对与读写使用独占锁,吞吐和性能差。

  1. CAS操作数据:table数组的取值/设置值、链表的数值操作、sizeCtl修改都利用CAS来完成,当因为其他线程修改了数据导致操作失败后,会自旋重试直到成功,保证了在多线程环境下的数据安全。
  2. synchronized互斥锁:操作链表/树种的元素时,使用synchronized锁,将第一个结点作为监视器锁,保证线程安全。
  3. volatile修饰变量:table、baseCount、CounterCell[]、sizeCtl等变量用volatile修饰,保证了多线程环境下数据读写的可见性。

1.7 segment 分段锁

img

不同Segment的并发写入

同一Segment的一写一读

同一Segment的并发写入 : Segment的写入是需要上锁的,因此对同一Segment的并发写入会被阻塞。

Get方法:

1.为输入的Key做Hash运算,得到hash值。

2.通过hash值,定位到对应的Segment对象

3.再次通过hash值,定位到Segment当中数组的具体位置。

Put方法:

1.为输入的Key做Hash运算,得到hash值。

2.通过hash值,定位到对应的Segment对象

3.获取可重入锁

4.再次通过hash值,定位到Segment当中数组的具体位置。

5.插入或覆盖HashEntry对象。

6.释放锁。

1.8

抛弃了原有的 Segment 分段锁,而采用了 CAS + synchronized 来保证并发安全性。

Why synchronize? 对 synchronized 获取锁的方式,JVM 使用了锁升级的优化方式,就是先使用偏向锁优先同一线程然后再次获取锁,如果失败,就升级为 CAS 轻量级锁,如果失败就会短暂自旋,防止线程被系统挂起。最后如果以上都失败就升级为重量级锁

summary

Instead of synchronizing every method on a common lock, restricting access to a single thread at a time, it uses a finer-grained locking mechanism called lock striping

he iterators returned by ConcurrentHashMap are weakly consistent instead of fail-fast., do not throw ConcurrentModificationException

size and isEmpty, have been slightly weakened to reflect the concurrent nature of the collection,size and isEmpty are far less useful in concurrent environments because these quantities are moving targets.

Additional Atomic Map Operations

put-if-absent, remove-if-equal, and replace-if-equal are implemented as atomic operations and specified by the ConcurrentMap interface


https://mp.weixin.qq.com/s?__biz=MzAxMjEwMzQ5MA==&mid=2448891092&idx=2&sn=3c1d8d8fd73f682fee647096e5a4dcc4&scene=21#wechat_redirect

https://mp.weixin.qq.com/s?__biz=MzAxMjEwMzQ5MA==&mid=2448891092&idx=2&sn=3c1d8d8fd73f682fee647096e5a4dcc4&scene=21#wechat_redirect

https://zhuanlan.zhihu.com/p/97902016

https://zhuanlan.zhihu.com/p/31614308