Java多线程--并发中集合的使用之ConcurrentSkipListMap

概述

      基于跳表实现的ConcurrentNavigableMap。

1)containsKey、get、put、remove等操作的平均时间复杂度为log(n);size非固定时间操作,因异步特性,需要遍历所有节点才能确定size,且可能不是正确的值如果遍历过程中有修改;批量操作:putAll、equals、toArray、containsValue、clear非原子性。

2)增删改查操作并发线程安全;

3)迭代器是弱一致性的:map创建时或之后某个时间点的,不抛出ConcurrentModificationException,可能与其他操作并发执行。升序视图及迭代器比降序的要快;

数据结构

      基于链表,有三种类型节点Node、Index、HeadIndex,底层为Node单链表有序层(升序),其他层为基于Node层的Index层即索引层,可能有多个索引层。

相对于单链表,跳表查找节点很快是在于:通过HeadIndex维护索引层次,通过Index从最上层开始往下查找元素,一步步缩小查找范围,到了最底层Node单链表层,就只需要比较很少的元素就可以找到待查找的元素节点。

[java] view plain copy
  1. // Node节点,拥有key-value对  
  2. // 单链表,有序,第一个节点为head.node标记节点,中间可能会穿插些删除标记节点(即marker节点)  
  3. static final class Node<K,V> {  
  4.     final K key;  
  5.     volatile Object value; // value为Object类型,便于区分删除标记节点、head.node标记节点  
  6.     volatile Node<K,V> next;  
  7.   
  8.     /** 
  9.      * Creates a new regular node. 
  10.      */  
  11.     Node(K key, Object value, Node<K,V> next) {  
  12.         this.key = key;  
  13.         this.value = value;  
  14.         this.next = next;  
  15.     }  
  16.   
  17.     // 创建一个删除标记节点  
  18.     // 删除标记节点的value为this,以区分其他Node节点;  
  19.     // key为null,其他场合会用到,但不能用作区分,因为head.node的key也为null  
  20.     Node(Node<K,V> next) {  
  21.         this.key = null;  
  22.         this.value = this;  
  23.         this.next = next;  
  24.     }  
  25.   
  26.     // CAS value属性  
  27.     boolean casValue(Object cmp, Object val) {  
  28.         return UNSAFE.compareAndSwapObject(this, valueOffset, cmp, val);  
  29.     }  
  30.   
  31.     // CAS next属性  
  32.     boolean casNext(Node<K,V> cmp, Node<K,V> val) {  
  33.         return UNSAFE.compareAndSwapObject(this, nextOffset, cmp, val);  
  34.     }  
  35.   
  36.     // 是否为删除标记节点  
  37.     boolean isMarker() {  
  38.         return value == this;  
  39.     }  
  40.   
  41.     // 是否为header node节点  
  42.     boolean isBaseHeader() {  
  43.         return value == BASE_HEADER;  
  44.     }  
  45.   
  46.     // 在当前Node节点后增加删除标记节点(采用CAS next方式实现)  
  47.     boolean appendMarker(Node<K,V> f) {  
  48.         return casNext(f, new Node<K,V>(f));  
  49.     }  
  50.   
  51.      // 推进删除Node节点  
  52.      // 一般在遍历过程中,如果遇到当前Node的value为null,会调用该方法  
  53.     void helpDelete(Node<K,V> b, Node<K,V> f) {  
  54.         // 首先检查当前的链接是否为b——>this——>f;  
  55.         // 再进行推进删除,过程分两步,每一步都采用CAS实现  
  56.         // 每次只推进一步,以减小推进线程间的干扰  
  57.         if (f == next && this == b.next) { // 检测是否为b——>this——>f,其中b为前驱节点,f为后继节点  
  58.             if (f == null || f.value != f) // 待删除节点未进行标记  
  59.                 appendMarker(f);// 链接删除标记节点  
  60.             else  
  61.                 b.casNext(this, f.next); // 删除当前节点及其删除标记节点,完成删除  
  62.         }  
  63.     }  
  64.   
  65.     // 获取节点的有效value  
  66.     V getValidValue() {  
  67.         Object v = value;  
  68.         if (v == this || v == BASE_HEADER) // 若为删除标记节点、header node节点,则返回null  
  69.             return null;  
  70.         return (V)v;  
  71.     }  
  72.   
  73.     // 对有效键值对封装到不可变的Entry  
  74.     AbstractMap.SimpleImmutableEntry<K,V> createSnapshot() {  
  75.         V v = getValidValue();  
  76.         if (v == null)  
  77.             return null;  
  78.         return new AbstractMap.SimpleImmutableEntry<K,V>(key, v);  
  79.     }  
  80.   
  81.     // UNSAFE mechanics  
  82.   
  83.     private static final sun.misc.Unsafe UNSAFE;  
  84.     private static final long valueOffset;  
  85.     private static final long nextOffset;  
  86.   
  87.     static {  
  88.         try {  
  89.             UNSAFE = sun.misc.Unsafe.getUnsafe();  
  90.             Class k = Node.class;  
  91.             valueOffset = UNSAFE.objectFieldOffset  
  92.                 (k.getDeclaredField("value"));  
  93.             nextOffset = UNSAFE.objectFieldOffset  
  94.                 (k.getDeclaredField("next"));  
  95.         } catch (Exception e) {  
  96.             throw new Error(e);  
  97.         }  
  98.     }  
  99. }  
  100.   
  101. // 索引节点,用于从最上层往下缩小查找范围  
  102. // 逻辑上的双链表,非前后链接,而是上下链接  
  103. static class Index<K,V> {  
  104.     final Node<K,V> node; // 索引节点是基于Node节点的  
  105.     final Index<K,V> down;// down为final的,简化并发  
  106.     volatile Index<K,V> right;  
  107.   
  108.     /** 
  109.      * Creates index node with given values. 
  110.      */  
  111.     Index(Node<K,V> node, Index<K,V> down, Index<K,V> right) {  
  112.         this.node = node;  
  113.         this.down = down;  
  114.         this.right = right;  
  115.     }  
  116.   
  117.     // CAS right属性  
  118.     final boolean casRight(Index<K,V> cmp, Index<K,V> val) {  
  119.         return UNSAFE.compareAndSwapObject(this, rightOffset, cmp, val);  
  120.     }  
  121.   
  122.     // 其Node节点是否删除  
  123.     final boolean indexesDeletedNode() {  
  124.         return node.value == null;  
  125.     }  
  126.   
  127.     // 链接Index节点  
  128.     // 如果链接过程中,其Node节点已删除,则不链接,以减小与解链接的CAS竞争  
  129.     /* 
  130.      * @param succ the expected current successor 
  131.      * @param newSucc the new successor 
  132.      * @return true if successful 
  133.      */  
  134.     final boolean link(Index<K,V> succ, Index<K,V> newSucc) {  
  135.         Node<K,V> n = node;  
  136.         newSucc.right = succ; // 将newSucc链接进来  
  137.         return n.value != null && casRight(succ, newSucc); // CAS right  
  138.     }  
  139.   
  140.     // 解链接index节点,如果其Node已删除,则解链接失败  
  141.     /** 
  142.      * @param succ the expected current successor 
  143.      * @return true if successful 
  144.      */  
  145.     final boolean unlink(Index<K,V> succ) {  
  146.         return !indexesDeletedNode() && casRight(succ, succ.right);// CAS right  
  147.     }  
  148.   
  149.     // Unsafe mechanics  
  150.     private static final sun.misc.Unsafe UNSAFE;  
  151.     private static final long rightOffset;  
  152.     static {  
  153.         try {  
  154.             UNSAFE = sun.misc.Unsafe.getUnsafe();  
  155.             Class k = Index.class;  
  156.             rightOffset = UNSAFE.objectFieldOffset  
  157.                 (k.getDeclaredField("right"));  
  158.         } catch (Exception e) {  
  159.             throw new Error(e);  
  160.         }  
  161.     }  
  162. }  
  163.   
  164. // HeadIndex节点,跟踪索引层次  
  165. static final class HeadIndex<K,V> extends Index<K,V> {  
  166.     final int level;// 索引层,从1开始,Node单链表层为0  
  167.     HeadIndex(Node<K,V> node, Index<K,V> down, Index<K,V> right, int level) {  
  168.         super(node, down, right);  
  169.         this.level = level;  
  170.     }  
  171. }  

JDK中一个实例结构图:

Java多线程--并发中集合的使用之ConcurrentSkipListMap

WIKI上关于跳表的解释图:

Java多线程--并发中集合的使用之ConcurrentSkipListMap

构造器

[java] view plain copy
  1. 无参构造,空Map  
  2. public ConcurrentSkipListMap() {  
  3.     this.comparator = null// 用Key的Comparable接口排序  
  4.     initialize();  
  5. }  
  6.   
  7. // 带comparator参数构造  
  8. public ConcurrentSkipListMap(Comparator<? super K> comparator) {  
  9.     this.comparator = comparator;  
  10.     initialize();  
  11. }  
  12.   
  13. // 带Map参数构造,采用Key的Comparable接口排序  
  14. public ConcurrentSkipListMap(Map<? extends K, ? extends V> m) {  
  15.     this.comparator = null;  
  16.     initialize();  
  17.     putAll(m);  
  18. }  
  19.   
  20. // 带SortedMap参数构造,采用SortedMap的comparator排序  
  21. public ConcurrentSkipListMap(SortedMap<K, ? extends V> m) {  
  22.     this.comparator = m.comparator();  
  23.     initialize();  
  24.     buildFromSorted(m);  
  25. }  

增删改查

初始化

[java] view plain copy
  1. final void initialize() {  
  2.     keySet = null;  
  3.     entrySet = null;  
  4.     values = null;  
  5.     descendingMap = null;  
  6.     randomSeed = seedGenerator.nextInt() | 0x0100// ensure nonzero  
  7.     head = new HeadIndex<K,V>(new Node<K,V>(null, BASE_HEADER, null),  
  8.                               nullnull1); // 初始化head节点,空Map  
  9. }  

增、改

      步骤:
1)查找比key小的前驱节点,查找过程中删除待删除Node节点的索引节点;
2)从前驱节点开始,遍历底层Node单链表,若已存在相关的key-value对,则CAS替换新的value,返回旧value;若不存在,则确定插入位置;遍历过程中,推进删除待删除的Node节点;
3)用key、value创建新的Node节点,用CAS next方式链接进来;
4)给新的Node节点随机生成一个索引层次,若层次大于0,则给其增加索引节点,返回null。

[java] view plain copy
  1. public V put(K key, V value) {  
  2.     if (value == null)  
  3.         throw new NullPointerException();  
  4.     return doPut(key, value, false);  
  5. }  
  6.   
  7. private V doPut(K kkey, V value, boolean onlyIfAbsent) {  
  8.     Comparable<? super K> key = comparable(kkey);  
  9.     for (;;) {  
  10.         Node<K,V> b = findPredecessor(key); // 找到前驱节点后,接下来就是在Node单链表层精确找到插入位置  
  11.         Node<K,V> n = b.next;  
  12.         for (;;) {  
  13.             // 遍历清除Node节点操作同findNode  
  14.             if (n != null) {  
  15.                 Node<K,V> f = n.next;  
  16.                 if (n != b.next)   
  17.                     break;  
  18.                 Object v = n.value;  
  19.                 if (v == null) {   
  20.                     n.helpDelete(b, f);   
  21.                     break;  
  22.                 }  
  23.                 if (v == n || b.value == null)  
  24.                     break;  
  25.                 int c = key.compareTo(n.key);  
  26.                 if (c > 0) { // key大于n,继续往后找  
  27.                     b = n;  
  28.                     n = f;  
  29.                     continue;  
  30.                 }  
  31.                 if (c == 0) { // 已有相关的key-value对  
  32.                     if (onlyIfAbsent || n.casValue(v, value))  
  33.                         return (V)v;  
  34.                     else  
  35.                         break// CAS value失败,则重新开始,失败原因可能是n变成了待删除节点或有其他修改线程修改过  
  36.                 }  
  37.                 // else c < 0; fall through:说明新增的key-value对需要插到b和n之间  
  38.             }  
  39.   
  40.             Node<K,V> z = new Node<K,V>(kkey, value, n);  
  41.             if (!b.casNext(n, z)) // 将新节点z插入b、n之间  
  42.                 break;         // 失败了,原因同n != b.next,重来  
  43.             int level = randomLevel(); // 给新增的Node节点随机生成一个索引层次  
  44.             if (level > 0)  
  45.                 insertIndex(z, level); // 给z增加索引节点  
  46.             return null;  
  47.         }  
  48.     }  
  49. }  
  50.   
  51. // 查找比key小的前驱节点,若没有,则返回head.node  
  52. // 一些操作依赖该方法删除索引节点  
  53. private Node<K,V> findPredecessor(Comparable<? super K> key) {  
  54.     if (key == null)  
  55.         throw new NullPointerException(); // don't postpone errors  
  56.     for (;;) {  
  57.         Index<K,V> q = head;  
  58.         Index<K,V> r = q.right;  
  59.         // 从索引层最上层开始,往右往下,  
  60.         // 一直找到最下层索引层(即第一层),从而确定查找范围,以在底层Node单链表遍历精确找到  
  61.         for (;;) {  
  62.             if (r != null) { // 在索引层,往右找  
  63.                 Node<K,V> n = r.node;  
  64.                 K k = n.key;  
  65.                 if (n.value == null) { // 遍历到待删除节点n的索引节点  
  66.                     if (!q.unlink(r))// 删除其索引节点(采用CAS right属性)  
  67.                         //删除失败原因:q被标记为待删除节点或在q后增加新索引节点或已删除了其right节点  
  68.                         break;   // 重新开始  
  69.                     r = q.right;// 若删除成功,则获取新的right索引节点,继续找  
  70.                     continue;  
  71.                 }  
  72.                 if (key.compareTo(k) > 0) { // 若key大,说明可能还有小于key的更大的,继续找  
  73.                     q = r;  
  74.                     r = r.right;  
  75.                     continue;  
  76.                 }  
  77.             }  
  78.             Index<K,V> d = q.down;// 当层索引层没有,则往下一层找,进一步缩小查找范围  
  79.             if (d != null) {// 在下一层索引层,继续找  
  80.                 q = d;  
  81.                 r = d.right;  
  82.             } else  
  83.                 return q.node;// 确定前驱节点,如果没有则为head.node标记节点  
  84.         }  
  85.     }  
  86. }  
  87.   
  88. // 给新增的Node节点随机生成一个索引层次  
  89. /** 
  90.      * Returns a random level for inserting a new node. 
  91.      * Hardwired to k=1, p=0.5, max 31 (see above and 
  92.      * Pugh's "Skip List Cookbook", sec 3.4). 
  93.      * 
  94.      * This uses the simplest of the generators described in George 
  95.      * Marsaglia's "Xorshift RNGs" paper.  This is not a high-quality 
  96.      * generator but is acceptable here. 
  97.      */  
  98. private int randomLevel() {  
  99.     int x = randomSeed;  
  100.     x ^= x << 13;  
  101.     x ^= x >>> 17;  
  102.     randomSeed = x ^= x << 5;  
  103.     if ((x & 0x80000001) != 0// test highest and lowest bits  
  104.         return 0;  
  105.     int level = 1;  
  106.     while (((x >>>= 1) & 1) != 0) ++level;  
  107.     return level;  
  108. }  
  109.   
  110. // 为Node节点添加索引节点  
  111. /** 
  112.      * @param z the node 
  113.      * @param level the level of the index 
  114.      */  
  115. private void insertIndex(Node<K,V> z, int level) {  
  116.     HeadIndex<K,V> h = head;  
  117.     int max = h.level; // head的索引层次是最大的  
  118.   
  119.     if (level <= max) { // 待添加索引节点的索引层次在head索引层次内,创建索引节点添加进来即可  
  120.         Index<K,V> idx = null;  
  121.         for (int i = 1; i <= level; ++i)  
  122.             idx = new Index<K,V>(z, idx, null);// 索引节点,从下往上链接  
  123.         addIndex(idx, h, level);               // 将索引节点链接进来  
  124.   
  125.     } else { // 增加一层索引层,需要new新层次的HeadIndex  
  126.         /* 
  127.          * To reduce interference by other threads checking for 
  128.          * empty levels in tryReduceLevel, new levels are added 
  129.          * with initialized right pointers. Which in turn requires 
  130.          * keeping levels in an array to access them while 
  131.          * creating new head index nodes from the opposite 
  132.          * direction. 
  133.          */  
  134.         level = max + 1;  
  135.         Index<K,V>[] idxs = (Index<K,V>[])new Index[level+1];  
  136.         Index<K,V> idx = null;  
  137.         for (int i = 1; i <= level; ++i)  
  138.             idxs[i] = idx = new Index<K,V>(z, idx, null);  
  139.   
  140.         HeadIndex<K,V> oldh;  
  141.         int k;  
  142.         for (;;) {  
  143.             oldh = head;  
  144.             int oldLevel = oldh.level;  
  145.             if (level <= oldLevel) { // 其他线程增加过索引层  
  146.                 k = level;  
  147.                 break;               // 同上面的level <= max情况处理  
  148.             }  
  149.             HeadIndex<K,V> newh = oldh;  
  150.             Node<K,V> oldbase = oldh.node;  
  151.             for (int j = oldLevel+1; j <= level; ++j) // 有可能其他线程删除过索引层,所以从oldLevel至level增加HeadIndex  
  152.                 newh = new HeadIndex<K,V>(oldbase, newh, idxs[j], j); // 创建新层次的HeadIndex且将索引节点idxs相应层次链接进来  
  153.             if (casHead(oldh, newh)) { // CAS head HeadIndex节点  
  154.                 k = oldLevel;  
  155.                 break;  
  156.             }  
  157.         }  
  158.         addIndex(idxs[k], oldh, k);                  // 需要将idxs的旧oldLevel层次及下面的索引链接进来  
  159.     }  
  160. }  
  161.   
  162. /** 
  163.  * 从第indexLevel层往下到第1层,将索引节点链接进来 
  164.  * @param idx the topmost index node being inserted 
  165.  * @param h the value of head to use to insert. This must be 
  166.  * snapshotted by callers to provide correct insertion level 
  167.  * @param indexLevel the level of the index 
  168.  */  
  169. private void addIndex(Index<K,V> idx, HeadIndex<K,V> h, int indexLevel) {  
  170.     // Track next level to insert in case of retries  
  171.     int insertionLevel = indexLevel;  
  172.     Comparable<? super K> key = comparable(idx.node.key);  
  173.     if (key == nullthrow new NullPointerException();  
  174.   
  175.     // 过程与findPredecessor类似, 只是多了增加索引节点  
  176.     for (;;) {  
  177.         int j = h.level;  
  178.         Index<K,V> q = h;  
  179.         Index<K,V> r = q.right;  
  180.         Index<K,V> t = idx;  
  181.         for (;;) {  
  182.             if (r != null) {// 在索引层,往右遍历  
  183.                 Node<K,V> n = r.node;  
  184.                 // compare before deletion check avoids needing recheck  
  185.                 int c = key.compareTo(n.key);  
  186.                 if (n.value == null) {   
  187.                     if (!q.unlink(r))  
  188.                         break;  
  189.                     r = q.right;  
  190.                     continue;  
  191.                 }  
  192.                 if (c > 0) {  
  193.                     q = r;  
  194.                     r = r.right;  
  195.                     continue;  
  196.                 }  
  197.             }  
  198.   
  199.             if (j == insertionLevel) {        // 可以链接索引节点idx  
  200.                 if (t.indexesDeletedNode()) { // 索引节点的Node节点被标记为待删除节点  
  201.                     findNode(key);            // 推进删除索引节点及其Node节点  
  202.                     return;                   // 不用增加索引节点了  
  203.                 }  
  204.                 if (!q.link(r, t))            // 将第insertionLevel层索引节点链接进来  
  205.                     //删除失败原因:同findPredecessor种的q.unlink(r)  
  206.                     break;                    // 链接失败,重新开始  
  207.                 if (--insertionLevel == 0) {  // 准备链接索引节点idx的下一层索引  
  208.                     if (t.indexesDeletedNode()) // 返回前再次检查索引节点t是否被标记为待删除节点,以进行清理工作  
  209.                         findNode(key);  
  210.                     return;                   // insertionLevel==0表明已经完成索引节点idx的链接  
  211.                 }  
  212.             }  
  213.   
  214.             if (--j >= insertionLevel && j < indexLevel) // 已链接过索引节点idx的第insertionLevel+1层  
  215.                 t = t.down;                              // 准备链接索引节点idx的第insertionLevel层  
  216.             q = q.down;                       // 准备链接索引节点idx的下一层索引  
  217.             r = q.right;  
  218.         }  
  219.     }  
  220. }  
  221.   
  222. // 查找相关key的Node,没有则返回null。  
  223. // 遍历Node单链表中,清除待删除节点  
  224. // 在doPut、doRemove、findNear等都包含这样的遍历清除操作  
  225. // 不能共享这样的清除代码,因为增删改查需要获取Node链表顺序的快照暂存到自身的局部变量,用于并发  
  226. // 一些操作依赖此方法删除Node节点  
  227. private Node<K,V> findNode(Comparable<? super K> key) {  
  228.     for (;;) {  
  229.         Node<K,V> b = findPredecessor(key); // 获取key的前驱节点  
  230.         Node<K,V> n = b.next;  
  231.         for (;;) {  
  232.             if (n == null)  
  233.                 return null;  
  234.             Node<K,V> f = n.next;  
  235.             // 不是连续的b——>n——>f快照,不能进行后续解链接待删除节点  
  236.             //变化情况:在b后增加了新节点或删除了其next节点或增加了删除标记节点以删除b,  
  237.             if (n != b.next)                
  238.                 break// 重新开始  
  239.             Object v = n.value;  
  240.             if (v == null) {           // n为待删除节点  
  241.                 n.helpDelete(b, f);    // 推进删除节点n  
  242.                 break;                 // 重新开始  
  243.             }  
  244.             // 返回的前驱节点b为待删除节点  
  245.             // 这里不能直接删除b,因为不知道b的前驱节点,只能重新开始,调用findPredecessor返回更前的节点  
  246.             if (v == n || b.value == null)  // b is deleted  
  247.                 break;                 // 重新开始  
  248.             int c = key.compareTo(n.key);  
  249.             if (c == 0)  
  250.                 return n;  
  251.             if (c < 0)  
  252.                 return null;  
  253.             b = n;  
  254.             n = f;  
  255.         }  
  256.     }  
  257. }  

      步骤:
1)查找比key小的前驱节点;
2)从前驱节点开始,遍历底层Node单链表,若不存在相关的key-value对,则返回null;否则确定Node节点位置;假设确定删除的节点为n,b为其前驱节点,f为其后继节点:

Java多线程--并发中集合的使用之ConcurrentSkipListMap
3)用CAS方式将其value置为null;

      作用:

      a)其他增删改查线程遍历到该节点时,都知其为待删除节点;

      b)其他增删改查线程可通过CAS修改n的next,推进n的删除。

该步失败,只需要重试即可。
4)在其后添加删除标记节点marker;

Java多线程--并发中集合的使用之ConcurrentSkipListMap
      作用:

      a)新增节点不能插入到n的后面;

      b)基于CAS方式的删除,可以避免删除上的错误。

5)删除该节点及其删除标记节点;

Java多线程--并发中集合的使用之ConcurrentSkipListMap
第4)5)步可能会失败,原因在于其他操作线程在遍历过程中知n的value为null后,会帮助推进删除n,这些帮助操作可以保证没有一个线程因为删除线程的删除操作而阻塞。

另外,删除需要确保b——>n——>marker——>f链接关系才能进行。

6)用findPredecessor删除其索引节点;
7)若最上层索引层无Node索引节点,则尝试降低索引层次。
8)返回其旧value

[java] view plain copy
  1. public V remove(Object key) {  
  2.     return doRemove(key, null);  
  3. }  
  4.   
  5. // 主要的删除Node节点及其索引节点方法  
  6. final V doRemove(Object okey, Object value) {  
  7.     Comparable<? super K> key = comparable(okey);  
  8.     for (;;) {  
  9.         Node<K,V> b = findPredecessor(key);  
  10.         Node<K,V> n = b.next;  
  11.         for (;;) {  
  12.             if (n == null)  
  13.                 return null;  
  14.             Node<K,V> f = n.next;  
  15.             if (n != b.next)                    // inconsistent read  
  16.                 break;  
  17.             Object v = n.value;  
  18.             if (v == null) {                    // n is deleted  
  19.                 n.helpDelete(b, f);  
  20.                 break;  
  21.             }  
  22.             if (v == n || b.value == null)      // b is deleted  
  23.                 break;  
  24.             int c = key.compareTo(n.key);  
  25.             if (c < 0)  
  26.                 return null;  
  27.             if (c > 0) {  
  28.                 b = n;  
  29.                 n = f;  
  30.                 continue;  
  31.             }  
  32.             if (value != null && !value.equals(v))  
  33.                 return null;  
  34.             if (!n.casValue(v, null))                   // 将value置为null  
  35.                 break;  
  36.             if (!n.appendMarker(f) || !b.casNext(n, f)) // 添加删除标记节点,删除该节点与其删除标记节点  
  37.                 findNode(key);                          // 失败则用findNode继续删除  
  38.             else {  
  39.                 findPredecessor(key);                   // 用findPredecessor删除其索引节点  
  40.                 if (head.right == null)  
  41.                     tryReduceLevel();  
  42.             }  
  43.             return (V)v;  
  44.         }  
  45.     }  
  46. }  
  47.   
  48. // 当最上三层索引层无Node索引节点,则将最上层索引层去掉。  
  49. // 采用CAS方式去掉后,如果其又拥有Node索引节点,则尝试将其恢复。  
  50. private void tryReduceLevel() {  
  51.     HeadIndex<K,V> h = head;  
  52.     HeadIndex<K,V> d;  
  53.     HeadIndex<K,V> e;  
  54.     if (h.level > 3 &&  
  55.         (d = (HeadIndex<K,V>)h.down) != null &&  
  56.         (e = (HeadIndex<K,V>)d.down) != null &&  
  57.         e.right == null &&  
  58.         d.right == null &&  
  59.         h.right == null &&  
  60.         casHead(h, d) && // try to set  
  61.         h.right != null// recheck  
  62.         casHead(d, h);   // try to backout  
  63. }  

      步骤:
1)查找比key小的前驱节点;
2)从前驱节点开始,遍历底层Node单链表,若不存在相关的key-value对,则返回null;否则获取Node节点;
3)判断其value是否为null,如果不为null,则直接返回value;否则重试,原因是其被标记为待删除节点。

[java] view plain copy
  1. public V get(Object key) {  
  2.     return doGet(key);  
  3. }  
  4.   
  5. private V doGet(Object okey) {  
  6.     Comparable<? super K> key = comparable(okey);  
  7.     /* 
  8.      * Loop needed here and elsewhere in case value field goes 
  9.      * null just as it is about to be returned, in which case we 
  10.      * lost a race with a deletion, so must retry. 
  11.      */  
  12.     for (;;) {  
  13.         Node<K,V> n = findNode(key);  
  14.         if (n == null)  
  15.             return null;  
  16.         Object v = n.value;  
  17.         if (v != null)  
  18.             return (V)v;  
  19.     }  
  20. }  

迭代器

      基础迭代器为Iter,从first节点开始遍历Node单链表层:

[java] view plain copy
  1. abstract class Iter<T> implements Iterator<T> {  
  2.     /** the last node returned by next() */  
  3.     Node<K,V> lastReturned;  
  4.     /** the next node to return from next(); */  
  5.     Node<K,V> next;  
  6.     /** Cache of next value field to maintain weak consistency */  
  7.     V nextValue;  
  8.   
  9.     /** Initializes ascending iterator for entire range. */  
  10.     Iter() {  
  11.         for (;;) {  
  12.             next = findFirst();  
  13.             if (next == null)  
  14.                 break;  
  15.             Object x = next.value;  
  16.             if (x != null && x != next) {  
  17.                 nextValue = (V) x;  
  18.                 break;  
  19.             }  
  20.         }  
  21.     }  
  22.   
  23.     public final boolean hasNext() {  
  24.         return next != null;  
  25.     }  
  26.   
  27.     /** Advances next to higher entry. */  
  28.     final void advance() {  
  29.         if (next == null)  
  30.             throw new NoSuchElementException();  
  31.         lastReturned = next;  
  32.         for (;;) {  
  33.             next = next.next; // next  
  34.             if (next == null)  
  35.                 break;  
  36.             Object x = next.value;  
  37.             if (x != null && x != next) {  
  38.                 nextValue = (V) x;  
  39.                 break;  
  40.             }  
  41.         }  
  42.     }  
  43.   
  44.     public void remove() {  
  45.         Node<K,V> l = lastReturned;  
  46.         if (l == null)  
  47.             throw new IllegalStateException();  
  48.         // It would not be worth all of the overhead to directly  
  49.         // unlink from here. Using remove is fast enough.  
  50.         ConcurrentSkipListMap.this.remove(l.key);  
  51.         lastReturned = null;  
  52.     }  
  53.   
  54. }  

特性

如何实现增删改查并发线程安全?

1. 采用无锁并发方式;

2.基于final、volatile、CAS方式助于并发;

3. 删除Node节点方式:将该节点的value置为null,且在其后插入一个删除标记节点,即:b——>n——>marker——>f(假设n为待删除Node节点,marker为其删除标记节点,b为n的前驱节点,f为n的删除前的后继节点)这种方式解决了4个问题:

      1)与Node插入可并发进行,因为n后为marker标记节点,肯定不会在n后插入新的Node节点;

      2)与Node修改可并发进行,因为n的value为null,修改线程对n的CAS修改肯定是失败的;

      3)与Node读可并发进行,因为n的value为null,即使读线程匹配到n,也返回的value为null,而在Map中返回null即代表key-value对不存在,n正在删除,所以也表明不存在,尽管不是严格意义上的;

      4)所有操作在遍历Node单链表时,可根据以上链接关系,推进删除n和marker