1)核心数据结构解析:
笔记:
基于跳表,是一个分层的结构。
从最上面开始查找,最后层层往下查。
2)demo
package org.example.concurrentskiplistmap;
import ma.glasnost.orika.jsr166x.ConcurrentNavigableMap;
import ma.glasnost.orika.jsr166x.ConcurrentSkipListMap;
public class ConcurrentSkipListMapTest {
public static void main(String[] args) {
ConcurrentSkipListMap<Integer, Integer> map = new ConcurrentSkipListMap<>();
// api1: put
map.put(2, 2);
map.put(1, 1);
map.put(3, 1);
// 输出:{1=1, 2=2, 3=1}
// 笔记: 可以看出,是顺序访问的. 可传入:(o1, o2) -> o2 - o1 指定排序规则
// 和插入的顺序不同,是排序过了
System.out.println(map);
//api2: subMap
// 输出: {3=1}
// 笔记:[),可以看出是查找的key的范围
map.put(4, 5);
ConcurrentNavigableMap<Integer, Integer> subMap = map.subMap(3, 4);
System.out.println(subMap);
}
}
3)put源码分析
private V doPut(K kkey, V value, boolean onlyIfAbsent) {
Comparable<K> key = comparable(kkey);
for (;;) {
Node<K,V> b = findPredecessor(key);
Node<K,V> n = b.next;
for (;;) {
if (n != null) {
Node<K,V> f = n.next;
if (n != b.next) // inconsistent read
break;
Object v = n.value;
if (v == null) { // n is deleted
n.helpDelete(b, f);
break;
}
if (v == n || b.value == null) // b is deleted
break;
int c = key.compareTo(n.key);
if (c > 0) {
b = n;
n = f;
continue;
}
if (c == 0) {
if (onlyIfAbsent || n.casValue(v, value))
return (V)v;
else
break; // restart if lost race to replace value
}
// else c < 0; fall through
}
Node<K,V> z = new Node<K,V>(kkey, value, n);
// 这个是核心点,里面是cas算法,看看值被修改没有
if (!b.casNext(n, z))
// 这里出现break了,其实就是多线程修改了,那么会从新到第一个for循环开搞
break; // restart if lost race to append to b
int level = randomLevel();
if (level > 0)
insertIndex(z, level);
return null;
}
}
}
也就是修改的话,都是通过cas来的,看着并没有考虑ABA这种问题
// 当前this和cmp比较,如果相等,就变为val这个新值
boolean casNext(Node<K,V> cmp, Node<K,V> val) {
return nextUpdater.compareAndSet(this, cmp, val);
}
// 这点有点强大,java中的cas竟然是可以直接针对Node中这种自定义的类型
static final AtomicReferenceFieldUpdater<Node, Node>
nextUpdater = AtomicReferenceFieldUpdater.newUpdater
(Node.class, Node.class, "next");
总结:可以看出,这种cas操作,往往都是双重for死循环,一直在cas判断如果等于预期值才做指定操作,然后return掉(退出2个for循环的办法)。
否则说明被多线程修改了,break掉第2个for循环,然后从第1个for循环开始不断地去重试。