ConcurrentHashMap线程安全的总结是我从源码分析出来的:
ConcurrentHashMap所谓线程安全是如果没有哈希冲突使用compareAndSwapObject方式新增节点,如果哈希冲突的时候锁住哈希冲突的节点,这样新增的节点是线程安全的,而 ConcurrentHashMap又不像hashtable那样整个put方法被锁定,所以性能比hashtable要好,因为这样不影响其他节点的插入和读取。
ConcurrentHashMap使用CAS技术插入新的Node,在添加到一个empty bin的时候。CAS是项乐观锁技术,当多个线程尝试使用CAS同时更新同一个变量时,只有其中一个线程能更新变量的值,而其它线程都失败,失败的线程并不会被挂起,而是被告知这次竞争中失败,并可以再次尝试。
具体看下面完整的分析过程就知道了。
- Map<String, String> cm = new ConcurrentHashMap<String, String>();
- for (int i = 0; i < 20; i++) {
- cm.put((char) (i + 65) + (char) (i + 66) + (char) (i + 67) + "", i + ">>>http://blog.csdn.net/unix21/");
- }
注释写的很清楚
- /* ---------------- Public operations -------------- */
-
- /**
- * Creates a new, empty map with the default initial table size (16).
- */
- public ConcurrentHashMap() {
- }
再到
- public abstract class AbstractMap<K,V> implements Map<K,V> {
-
-
-
-
- protected AbstractMap() {
- }
-
-
-
-
-
-
-
-
-
- public int size() {
- return entrySet().size();
- }
第一次put
![](https://img-blog.csdn.net/20160318105354203)
下面是完整的
-
- 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;
- 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;
- }
- 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;
- }
- }
- }
- }
- if (binCount != 0) {
- if (binCount >= TREEIFY_THRESHOLD)
- treeifyBin(tab, i);
- if (oldVal != null)
- return oldVal;
- break;
- }
- }
- }
- addCount(1L, binCount);
- return null;
- }
可以看出ConcurrentHashMap不是像hashTable一样整个put方法synchronized
![](https://img-blog.csdn.net/20160318111143453)
initTable()
![](https://img-blog.csdn.net/20160318105849333)
Thread.yield(); // lost initialization race; just spin
![](https://img-blog.csdn.net/20160318111354079)
U.compareAndSwapInt
compareAndSwapInt() 是sun.misc.Unsafe类中的一个本地方法。
对此,我们需要了解的是 compareAndSetState(expect, update) 是以原子的方式操作当前线程;若当前线程的状态为expect,则设置它的状态为update。
![](https://img-blog.csdn.net/20160318111818127)
下一步
![](https://img-blog.csdn.net/20160318111920893)
回到putVal
![](https://img-blog.csdn.net/20160318112129238)
下一步
![](https://img-blog.csdn.net/20160318112214129)
这次无需初始化了
![](https://img-blog.csdn.net/20160318110433106)
进入casTabAt,又用到了U.compareAndSwapObject完成新节点的插入
![](https://img-blog.csdn.net/20160318110539310)
关于CAS https://en.wikipedia.org/wiki/Compare-and-swap
C语言实现
- int compare_and_swap(int* reg, int oldval, int newval)
- {
- ATOMIC();
- int old_reg_val = *reg;
- if (old_reg_val == oldval)
- *reg = newval;
- END_ATOMIC();
- return old_reg_val;
- }
要实现无锁(lock-free)的非阻塞算法有多种实现方法,其中CAS(比较与交换,Compare and swap)是一种有名的无锁算法。
CAS, CPU指令,在大多数处理器架构,包括IA32、Space中采用的都是CAS指令,CAS的语义是“我认为V的值应该为A,如果是,那么将V的值更新为B,否则不修改并告诉V的值实际为多少”,
CAS是项乐观锁技术,当多个线程尝试使用CAS同时更新同一个变量时,只有其中一个线程能更新变量的值,而其它线程都失败,失败的线程并不会被挂起,而是被告知这次竞争中失败,并可以再次尝试。
CAS有3个操作数,内存值V,旧的预期值A,要修改的新值B。当且仅当预期值A和内存值V相同时,将内存值V修改为B,否则什么都不做。
参考:非阻塞同步算法与CAS(Compare and Swap)无锁算法
回到putval
![](https://img-blog.csdn.net/20160318112456039)
和hashmap和hashtable一样,ConcurrentHashMap内部也是有一个静态嵌套类实现节点的
- static class Node<K,V> implements Map.Entry<K,V> {
- final int hash;
- final K key;
- volatile V val;
- volatile Node<K,V> next;
-
- Node(int hash, K key, V val, Node<K,V> next) {
- this.hash = hash;
- this.key = key;
- this.val = val;
- this.next = next;
- }
下一步
![](https://img-blog.csdn.net/20160318112641521)
至此完成第一次put
第二次put
![](https://img-blog.csdn.net/20160318112800043)
又调用casTabAt(tab, i, null,
new Node<K,V>(hash, key, value, null))插入新节点
![](https://img-blog.csdn.net/20160318112921983)
第2个节点插入完成
![](https://img-blog.csdn.net/20160318113006187)
下一步
![](https://img-blog.csdn.net/20160318113142002)
下一步
![](https://img-blog.csdn.net/20160318113324243)
下一步
![](https://img-blog.csdn.net/20160318113458224)
下一步
![](https://img-blog.csdn.net/20160318113601181)
下一步
![](https://img-blog.csdn.net/20160318113658010)
下一步
![](https://img-blog.csdn.net/20160318113829620)
至此完成第二次put
第三次put
![](https://img-blog.csdn.net/20160318114805914)
下一步,i=6 f=tabat(6) =null,这样就在这个索引插值
![](https://img-blog.csdn.net/20160318114909634)
下一步
![](https://img-blog.csdn.net/20160318115103343)
下一步
![](https://img-blog.csdn.net/20160318115206404)
第三次put完成
经过几次put都和第三步一样,第11次put又进入到synchronized (f)代码块,
因为这次i=0,而f=tab[0]不为null
![](https://img-blog.csdn.net/20160318115552768)
从上面的代码可以看到f被锁定
![](https://img-blog.csdn.net/20160318115930721)
下一步,e=f pred=e,新节点插
![](https://img-blog.csdn.net/20160318120127581)
下一步,看出新节点插在之前节点的next后面
![](https://img-blog.csdn.net/20160318120414091)
总结:这样就看出ConcurrentHashMap可以保证哈希冲突的时候新增节点的线程安全性
Hashtable实现原理以及线程安全原因请参见:http://blog.csdn.net/unix21/article/details/50920708