ConcurrentSkipListMap/ConcurrentSkipListSet

转关于ConcurrentSkipListMap 和 ConcurrentSkipListSet 的深度好文, 终于明白了skip List (跳表)的含义html

http://www.cnblogs.com/skywang12345/p/3498634.htmlnode

http://www.cnblogs.com/skywang12345/p/3498556.html算法

 =====安全

ConcurrentSkipListMap介绍

ConcurrentSkipListMap是线程安全的有序的哈希表,适用于高并发的场景。
ConcurrentSkipListMap和TreeMap,它们虽然都是有序的哈希表。可是,第一,它们的线程安全机制不一样,TreeMap是非线程安全的,而ConcurrentSkipListMap是线程安全的。第二,ConcurrentSkipListMap是经过跳表实现的,而TreeMap是经过红黑树实现的。
关于跳表(Skip List),它是平衡树的一种替代的数据结构,可是和红黑树不相同的是,跳表对于树的平衡的实现是基于一种随机化的算法的,这样也就是说跳表的插入和删除的工做是比较简单的。数据结构

 

ConcurrentSkipListMap原理和数据结构

ConcurrentSkipListMap的数据结构,以下图所示:并发

说明高并发

先以数据“7,14,21,32,37,71,85”序列为例,来对跳表进行简单说明。spa

跳表分为许多层(level),每一层均可以看做是数据的索引,这些索引的意义就是加快跳表查找数据速度。每一层的数据都是有序的,上一层数据是下一层数据的子集,而且第一层(level 1)包含了所有的数据;层次越高,跳跃性越大,包含的数据越少。
跳表包含一个表头,它查找数据时,是从上往下,从左往右进行查找。如今“须要找出值为32的节点”为例,来对比说明跳表和广泛的链表。线程

状况1:链表中查找“32”节点
路径以下图1-02所示:指针

须要4步(红色部分表示路径)。

 

状况2:跳表中查找“32”节点
路径以下图1-03所示:

忽略索引垂直线路上路径的状况下,只须要2步(红色部分表示路径)。


下面说说Java中ConcurrentSkipListMap的数据结构。
(01) ConcurrentSkipListMap继承于AbstractMap类,也就意味着它是一个哈希表。
(02) Index是ConcurrentSkipListMap的内部类,它与“跳表中的索引相对应”。HeadIndex继承于Index,ConcurrentSkipListMap中含有一个HeadIndex的对象head,head是“跳表的表头”。
(03) Index是跳表中的索引,它包含“右索引的指针(right)”,“下索引的指针(down)”和“哈希表节点node”。node是Node的对象,Node也是ConcurrentSkipListMap中的内部类。

=========

ConcurrentSkipListSet介绍

ConcurrentSkipListSet是线程安全的有序的集合,适用于高并发的场景。
ConcurrentSkipListSet和TreeSet,它们虽然都是有序的集合。可是,第一,它们的线程安全机制不一样,TreeSet是非线程安全的,而ConcurrentSkipListSet是线程安全的。第二,ConcurrentSkipListSet是经过ConcurrentSkipListMap实现的,而TreeSet是经过TreeMap实现的。

 

ConcurrentSkipListSet原理和数据结构

ConcurrentSkipListSet的数据结构,以下图所示:

说明
(01) ConcurrentSkipListSet继承于AbstractSet。所以,它本质上是一个集合。
(02) ConcurrentSkipListSet实现了NavigableSet接口。所以,ConcurrentSkipListSet是一个有序的集合。
(03) ConcurrentSkipListSet是经过ConcurrentSkipListMap实现的。它包含一个ConcurrentNavigableMap对象m,而m对象其实是ConcurrentNavigableMap的实现类ConcurrentSkipListMap的实例。ConcurrentSkipListMap中的元素是key-value键值对;而ConcurrentSkipListSet是集合,它只用到了ConcurrentSkipListMap中的key!

本站公众号
   欢迎关注本站公众号,获取更多信息