ConcurrentHashMap实现原理-源码调试

来源:互联网 发布:sql降序排列 编辑:程序博客网 时间:2024/04/30 03:42
ConcurrentHashMap线程安全的总结是我从源码分析出来的:

ConcurrentHashMap所谓线程安全是如果没有哈希冲突使用compareAndSwapObject方式新增节点,如果哈希冲突的时候锁住哈希冲突的节点,这样新增的节点是线程安全的,而 ConcurrentHashMap又不像hashtable那样整个put方法被锁定,所以性能比hashtable要好,因为这样不影响其他节点的插入和读取。

ConcurrentHashMap使用CAS技术插入新的Node,在添加到一个empty bin的时候。CAS是项乐观锁技术,当多个线程尝试使用CAS同时更新同一个变量时,只有其中一个线程能更新变量的值,而其它线程都失败,失败的线程并不会被挂起,而是被告知这次竞争中失败,并可以再次尝试。

具体看下面完整的分析过程就知道了。

[java] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. Map<String, String> cm = new ConcurrentHashMap<String, String>();  
  2.         for (int i = 0; i < 20; i++) {  
  3.             cm.put((char) (i + 65) + (char) (i + 66) + (char) (i + 67) + "", i + ">>>http://blog.csdn.net/unix21/");  
  4.         }  


注释写的很清楚

[python] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. /* ---------------- Public operations -------------- */  
  2.   
  3.     /**  
  4.      * Creates a new, empty map with the default initial table size (16).  
  5.      */  
  6.     public ConcurrentHashMap() {  
  7.     }  


再到

[java] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. public abstract class AbstractMap<K,V> implements Map<K,V> {  
  2.     /** 
  3.      * Sole constructor.  (For invocation by subclass constructors, typically 
  4.      * implicit.) 
  5.      */  
  6.     protected AbstractMap() {  
  7.     }  
  8.   
  9.     // Query Operations  
  10.   
  11.     /** 
  12.      * {@inheritDoc} 
  13.      * 
  14.      * @implSpec 
  15.      * This implementation returns <tt>entrySet().size()</tt>. 
  16.      */  
  17.     public int size() {  
  18.         return entrySet().size();  
  19.     }  

 

第一次put

 

下面是完整的

[java] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. /** Implementation for put and putIfAbsent */  
  2.     final V putVal(K key, V value, boolean onlyIfAbsent) {  
  3.         if (key == null || value == nullthrow new NullPointerException();  
  4.         int hash = spread(key.hashCode());  
  5.         int binCount = 0;  
  6.         for (Node<K,V>[] tab = table;;) {  
  7.             Node<K,V> f; int n, i, fh;  
  8.             if (tab == null || (n = tab.length) == 0)  
  9.                 tab = initTable();  
  10.             else if ((f = tabAt(tab, i = (n - 1) & hash)) == null) {  
  11.                 if (casTabAt(tab, i, null,  
  12.                              new Node<K,V>(hash, key, value, null)))  
  13.                     break;                   // no lock when adding to empty bin  
  14.             }  
  15.             else if ((fh = f.hash) == MOVED)  
  16.                 tab = helpTransfer(tab, f);  
  17.             else {  
  18.                 V oldVal = null;  
  19.                 synchronized (f) {  
  20.                     if (tabAt(tab, i) == f) {  
  21.                         if (fh >= 0) {  
  22.                             binCount = 1;  
  23.                             for (Node<K,V> e = f;; ++binCount) {  
  24.                                 K ek;  
  25.                                 if (e.hash == hash &&  
  26.                                     ((ek = e.key) == key ||  
  27.                                      (ek != null && key.equals(ek)))) {  
  28.                                     oldVal = e.val;  
  29.                                     if (!onlyIfAbsent)  
  30.                                         e.val = value;  
  31.                                     break;  
  32.                                 }  
  33.                                 Node<K,V> pred = e;  
  34.                                 if ((e = e.next) == null) {  
  35.                                     pred.next = new Node<K,V>(hash, key,  
  36.                                                               value, null);  
  37.                                     break;  
  38.                                 }  
  39.                             }  
  40.                         }  
  41.                         else if (f instanceof TreeBin) {  
  42.                             Node<K,V> p;  
  43.                             binCount = 2;  
  44.                             if ((p = ((TreeBin<K,V>)f).putTreeVal(hash, key,  
  45.                                                            value)) != null) {  
  46.                                 oldVal = p.val;  
  47.                                 if (!onlyIfAbsent)  
  48.                                     p.val = value;  
  49.                             }  
  50.                         }  
  51.                     }  
  52.                 }  
  53.                 if (binCount != 0) {  
  54.                     if (binCount >= TREEIFY_THRESHOLD)  
  55.                         treeifyBin(tab, i);  
  56.                     if (oldVal != null)  
  57.                         return oldVal;  
  58.                     break;  
  59.                 }  
  60.             }  
  61.         }  
  62.         addCount(1L, binCount);  
  63.         return null;  
  64.     }  

 

可以看出ConcurrentHashMap不是像hashTable一样整个put方法synchronized

 

initTable()

Thread.yield(); // lost initialization race; just spin

 

U.compareAndSwapInt

compareAndSwapInt() 是sun.misc.Unsafe类中的一个本地方法。

对此,我们需要了解的是 compareAndSetState(expect, update) 是以原子的方式操作当前线程;若当前线程的状态为expect,则设置它的状态为update。

下一步

回到putVal

下一步

 

这次无需初始化了

 

进入casTabAt,又用到了U.compareAndSwapObject完成新节点的插入

关于CAS https://en.wikipedia.org/wiki/Compare-and-swap

C语言实现

[cpp] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. int compare_and_swap(int* reg, int oldval, int newval)  
  2. {  
  3.   ATOMIC();  
  4.   int old_reg_val = *reg;  
  5.   if (old_reg_val == oldval)  
  6.      *reg = newval;  
  7.   END_ATOMIC();  
  8.   return old_reg_val;  
  9. }  


 

要实现无锁(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

 

和hashmap和hashtable一样,ConcurrentHashMap内部也是有一个静态嵌套类实现节点的

[java] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. static class Node<K,V> implements Map.Entry<K,V> {  
  2.         final int hash;  
  3.         final K key;  
  4.         volatile V val;  
  5.         volatile Node<K,V> next;  
  6.   
  7.         Node(int hash, K key, V val, Node<K,V> next) {  
  8.             this.hash = hash;  
  9.             this.key = key;  
  10.             this.val = val;  
  11.             this.next = next;  
  12.         }  


下一步

至此完成第一次put

 

第二次put

 

又调用casTabAt(tab, i, null,
                             new Node<K,V>(hash, key, value, null))插入新节点

 

第2个节点插入完成

下一步

 

下一步

下一步

下一步

 

下一步

下一步

至此完成第二次put

 

第三次put

下一步,i=6  f=tabat(6)   =null,这样就在这个索引插值

下一步

下一步

第三次put完成

 

经过几次put都和第三步一样,第11次put又进入到synchronized (f)代码块,

因为这次i=0,而f=tab[0]不为null

 

从上面的代码可以看到f被锁定

 

下一步,e=f  pred=e,新节点插

下一步,看出新节点插在之前节点的next后面

总结:这样就看出ConcurrentHashMap可以保证哈希冲突的时候新增节点的线程安全性


Hashtable实现原理以及线程安全原因请参见:http://blog.csdn.net/unix21/article/details/50920708



0 0
原创粉丝点击