TreeMap、ConcurrentSkipListMap的关系
TreeMap是支持key有序排列的一个key-value数据结构,不过是在单线程情况下使用,并发下不是线程安全的。ConcurrentSkipListMap是基于跳表的实现,也是支持key有序排列的一个key-value数据结构,在并发情况下表现很好,是一种空间换时间的实现,ConcurrentSkipListMap是基于一种乐观锁的方式去实现高并发。

(这里借用一张网上的图片)
ConcurrentSkipListMap中用到了Node数据节点和Index索引节点的存储方式,通过volatile关键字实现了并发的操作。
static final class Node<K,V> {
final K key;
volatile Object value;//value值
volatile Node<K,V> next;//next引用
……
}
static class Index<K,V> {
final Node<K,V> node;
final Index<K,V> down;//down引用
volatile Index<K,V> right;//right引用
……
}
我们看Node数据,维护了一个next的Node节点,实现中全部的数据节点Node是一种链表的实现方式。Index节点则维护了当前Index节点的Node数据,以及Index的右引用和下引用。查找时Index节点当查到level=1时,即down引用为null时,就会根据当前的Index节点对应的Node节点的链表去查找key对应的数据。
下面从插入数据去看如何实现高并发
public V put(K key, V value) {
if (value == null)
throw new NullPointerException();
return doPut(key, value, false);
}
private V doPut(K kkey, V value, boolean onlyIfAbsent) {
Comparable<? super K> key = comparable(kkey);

本文探讨了ConcurrentSkipListMap作为高并发集合的实现,对比了它与TreeMap的区别。ConcurrentSkipListMap基于跳表,通过乐观锁确保线程安全,采用Node和Index节点实现并发操作。其内部使用volatile保证可见性,查找数据时,当Index节点的down引用为null时,会沿着Node链表查找目标key。
最低0.47元/天 解锁文章
444

被折叠的 条评论
为什么被折叠?



