一、ConcurrentHashMap
1.1 Java7 中的实现
ConcurrentHashMap 采用了分段锁技术,其中 Segment 继承于 ReentrantLock(可重入锁)。不会像 HashTable 那样不管是 put 还是 get 操作都需要做同步处理,理论上 ConcurrentHashMap 支持 CurrencyLevel (Segment 数组数量)的线程并发。每当一个线程占用锁访问一个 Segment 时,不会影响到其他的 Segment。
- 数据结构图示
- 成员变量
//定义的常量
//初始时默认容量
static final int DEFAULT_INITIAL_CAPACITY = 16;
//负载因子
static final float DEFAULT_LOAD_FACTOR = 0.75f;
//默认的并发等级,
static final int DEFAULT_CONCURRENCY_LEVEL = 16;
//最大容量
static final int MAXIMUM_CAPACITY = 1 << 30;
//最小每个Segment持有table数量,必须是2的倍数
static final int MIN_SEGMENT_TABLE_CAPACITY = 2;
//Segment 数组最大容量 65536
static final int MAX_SEGMENTS = 1 << 16;
//不加锁进行检索的数量
static final int RETRIES_BEFORE_LOCK = 2;
//Segment 数组, 数组中的每个元素都持有HashEntry 桶
final Segment<K,V>[] segments;
transient Set<K> keySet;
transient Set<Map.Entry<K,V>> entrySet;
transient Collection<V> values;
- Segment 的源码实现
static final class Segment<K,V> extends ReentrantLock implements Serializable {
private static final long serialVersionUID = 2249069246763182397L;
static final int MAX_SCAN_RETRIES =
Runtime.getRuntime().availableProcessors() > 1 ? 64 : 1;
//存放数据的hash 桶
transient volatile HashEntry<K,V>[] table;
transient int count;
transient int modCount;
transient int threshold;
final float loadFactor;
Segment(float lf, int threshold, HashEntry<K,V>[] tab) {
this.loadFactor = lf;
this.threshold = threshold;
this.table = tab;
}
}
Entry 实现
static final class HashEntry<K,V> {
final int hash; //hahs值
final K key; //键
volatile V value; //值
volatile HashEntry<K,V> next; //后继指针
HashEntry(int hash, K key, V value, HashEntry<K,V> next) {
this.hash = hash;
this.key = key;
this.value = value;
this.next = next;
}
}
构造函数
public ConcurrentHashMap(int initialCapacity,
float loadFactor, int concurrencyLevel) {
if (!(loadFactor > 0) || initialCapacity < 0 || concurrencyLevel <= 0)
throw new IllegalArgumentException();
if (concurrencyLevel > MAX_SEGMENTS)
concurrencyLevel = MAX_SEGMENTS;
// Find power-of-two sizes best matching arguments
int sshift = 0; //sshift等于ssize从1向左移位的次数
int ssize = 1; //Segment 数组的大小
//为了能通过按位与的散列算法来定位segments数组的索引,必须保证segments数组的长度是2的N次方
//(power-of-two size),所以必须计算出一个大于或等于concurrencyLevel的最小的2的N次方值
//来作为segments数组的长度。
while (ssize < concurrencyLevel) {
++sshift;
ssize <<= 1;
}
//segmentShift用于定位参与散列运算的位数
this.segmentShift = 32 - sshift;
//segmentMask是散列运算的掩码,等于ssize减1,即15,掩码的二进制各个位的值都是1
this.segmentMask = ssize - 1;
if (initialCapacity > MAXIMUM_CAPACITY)
initialCapacity = MAXIMUM_CAPACITY;
int c = initialCapacity / ssize;
if (c * ssize < initialCapacity)
++c;
int cap = MIN_SEGMENT_TABLE_CAPACITY;
while (cap < c)
cap <<= 1;
//创建 Segment,并放入Segment数组
Segment<K,V> s0 =
new Segment<K,V>(loadFactor, (int)(cap * loadFactor),
(HashEntry<K,V>[])new HashEntry[cap]);
Segment<K,V>[] ss = (Segment<K,V>[])new Segment[ssize];
UNSAFE.putOrderedObject(ss, SBASE, s0); // ordered write of segments[0]
this.segments = ss;
}
get 方法
public V get(Object key) {
Segment<K,V> s; // manually integrate access methods to reduce overhead
HashEntry<K,V>[] tab;
//对key 进行散列,得到hash值
int h = hash(key);
//计算出key 所在的segments数组下标
long u = (((h >>> segmentShift) & segmentMask) << SSHIFT) + SBASE;
if ((s = (Segment<K,V>)UNSAFE.getObjectVolatile(segments, u)) != null &&
(tab = s.table) != null) {
//遍历桶中的元素,找到key对应的的元素
for (HashEntry<K,V> e = (HashEntry<K,V>) UNSAFE.getObjectVolatile
(tab, ((long)(((tab.length - 1) & h)) << TSHIFT) + TBASE);
e != null; e = e.next) {
K k;
if ((k = e.key) == key || (e.hash == h && key.equals(k)))
return e.value;
}
}
return null;
}
get操作的高效之处在于整个get过程不需要加锁
- put 方法了解
public V put(K key, V value) {
Segment<K,V> s;
if (value == null)
throw new NullPointerException();
//对key 进行散列
int hash = hash(key);
//计算存放到哪个Segment
int j = (hash >>> segmentShift) & segmentMask;
if ((s = (Segment<K,V>)UNSAFE.getObject // nonvolatile; recheck
(segments, (j << SSHIFT) + SBASE)) == null) // in ensureSegment
s = ensureSegment(j);
return s.put(key, hash, value, false);
}
//如果不存在,创建Segment,并返回
private Segment<K,V> ensureSegment(int k) {
final Segment<K,V>[] ss = this.segments;
long u = (k << SSHIFT) + SBASE; // raw offset
Segment<K,V> seg;
if ((seg = (Segment<K,V>)UNSAFE.getObjectVolatile(ss, u)) == null) {
Segment<K,V> proto = ss[0]; // use segment 0 as prototype
int cap = proto.table.length;
float lf = proto.loadFactor;
int threshold = (int)(cap * lf);
HashEntry<K,V>[] tab = (HashEntry<K,V>[])new HashEntry[cap];
if ((seg = (Segment<K,V>)UNSAFE.getObjectVolatile(ss, u))
== null) { // recheck
Segment<K,V> s = new Segment<K,V>(lf, threshold, tab);
while ((seg = (Segment<K,V>)UNSAFE.getObjectVolatile(ss, u))
== null) {
if (UNSAFE.compareAndSwapObject(ss, u, null, seg = s))
break;
}
}
}
return seg;
}
找到对应的Segment,执行put 方法
final V put(K key, int hash, V value, boolean onlyIfAbsent) {
HashEntry<K,V> node = tryLock() ? null : //1
scanAndLockForPut(key, hash, value); //2
V oldValue;
try {
HashEntry<K,V>[] tab = table;
int index = (tab.length - 1) & hash;
HashEntry<K,V> first = entryAt(tab, index); //3
for (HashEntry<K,V> e = first;;) {
if (e != null) {
K k;
if ((k = e.key) == key ||
(e.hash == hash && key.equals(k))) {//4
oldValue = e.value;
if (!onlyIfAbsent) {
e.value = value;
++modCount;
}
break;
}
e = e.next;
}
else {//5
if (node != null)
node.setNext(first);
else
node = new HashEntry<K,V>(hash, key, value, first);
int c = count + 1;
if (c > threshold && tab.length < MAXIMUM_CAPACITY)
rehash(node);
else
setEntryAt(tab, index, node);
++modCount;
count = c;
oldValue = null;
break;
}
}
} finally {
unlock(); //6
}
return oldValue;
}
- 首先第一步的时候会尝试获取锁: tryLock()
- 如果获取失败肯定就有其他线程存在竞争,则利用 scanAndLockForPut() 自旋获取锁。
- 将当前 Segment 中的 table 通过 key 的 hashcode 定位到 HashEntry。
- 遍历该 HashEntry,如果不为空则判断传入的 key 和当前遍历的 key 是否相等,相等则覆盖旧的 value。
- 不为空则需要新建一个 HashEntry 并加入到 Segment 中,同时会先判断是否需要扩容。
- 最后会解除在 1 中所获取当前 Segment 的锁。
- scanAndLockForPut方法
private HashEntry<K,V> scanAndLockForPut(K key, int hash, V value) {
HashEntry<K,V> first = entryForHash(this, hash);
HashEntry<K,V> e = first;
HashEntry<K,V> node = null;
int retries = -1; // negative while locating node
while (!tryLock()) { //1
HashEntry<K,V> f; // to recheck first below
if (retries < 0) {
if (e == null) {
if (node == null) // speculatively create node
node = new HashEntry<K,V>(hash, key, value, null);
retries = 0;
}
else if (key.equals(e.key))
retries = 0;
else
e = e.next;
}
else if (++retries > MAX_SCAN_RETRIES) {//2
lock();
break;
}
else if ((retries & 1) == 0 &&
(f = entryForHash(this, hash)) != first) {
e = first = f; // re-traverse if entry changed
retries = -1;
}
}
return node;
}
- 尝试自旋获取锁。
- 如果重试的次数达到了 MAX_SCAN_RETRIES 则改为阻塞锁获取,保证能获取成功。
- rehash方法
private void rehash(HashEntry<K,V> node) {
HashEntry<K,V>[] oldTable = table;
int oldCapacity = oldTable.length;
int newCapacity = oldCapacity << 1; //1
threshold = (int)(newCapacity * loadFactor);
HashEntry<K,V>[] newTable =
(HashEntry<K,V>[]) new HashEntry[newCapacity];
int sizeMask = newCapacity - 1;
for (int i = 0; i < oldCapacity ; i++) {
HashEntry<K,V> e = oldTable[i];
if (e != null) {
HashEntry<K,V> next = e.next;
int idx = e.hash & sizeMask;
if (next == null) // Single node on list //2
newTable[idx] = e;
else { // Reuse consecutive sequence at same slot //3
HashEntry<K,V> lastRun = e;
int lastIdx = idx;
for (HashEntry<K,V> last = next;
last != null;
last = last.next) {
int k = last.hash & sizeMask;
if (k != lastIdx) {
lastIdx = k;
lastRun = last;
}
}
newTable[lastIdx] = lastRun;
// Clone remaining nodes
for (HashEntry<K,V> p = e; p != lastRun; p = p.next) {
V v = p.value;
int h = p.hash;
int k = h & sizeMask;
HashEntry<K,V> n = newTable[k];
newTable[k] = new HashEntry<K,V>(h, p.key, v, n);
}
}
}
}
int nodeIndex = node.hash & sizeMask; // add the new node
node.setNext(newTable[nodeIndex]);
newTable[nodeIndex] = node;
table = newTable;
}
- 计算新的容量为旧容量的2倍
- 遍历旧HashEntry桶,如果当前HashEntry只用一个节点,直接放到新的HashEntry桶中
- 如果当前HashEntry是链表,则遍历链表,重新计算下标放到新的HashEntry桶中
1.2 Java8 中的实现
- 数据结构图示
抛弃了原有的 Segment 分段锁,而采用了 CAS + synchronized 来保证并发安全性。结构上也引入了红黑树,防止查询效率退化为O(N)
Node类与Java7 HashEntry类似
static class Node<K,V> implements Map.Entry<K,V> {
final int hash;
final K key;
volatile V val; //volatile保证可见性
volatile Node<K,V> next;
Node(int hash, K key, V val, Node<K,V> next) {
this.hash = hash;
this.key = key;
this.val = val;
this.next = next;
}
}
get方法
public V get(Object key) {
Node<K,V>[] tab; Node<K,V> e, p; int n, eh; K ek;
int h = spread(key.hashCode());
if ((tab = table) != null && (n = tab.length) > 0 &&
(e = tabAt(tab, (n - 1) & h)) != null) {
//根据计算出来的 hashcode 寻址,如果就在桶上那么直接返回值。
if ((eh = e.hash) == h) {
if ((ek = e.key) == key || (ek != null && key.equals(ek)))
return e.val;
}
else if (eh < 0)//如果是红黑树那就按照树的方式获取值。
return (p = e.find(h, key)) != null ? p.val : null;
while ((e = e.next) != null) { 就不满足那就按照链表的方式遍历获取值。
if (e.hash == h &&
((ek = e.key) == key || (ek != null && key.equals(ek))))
return e.val;
}
}
return null;
}
- put 方法
final V putVal(K key, V value, boolean onlyIfAbsent) {
if (key == null || value == null) throw new NullPointerException();
int hash = spread(key.hashCode());
int binCount = 0;
for (Node<K,V>[] tab = table;;) {
Node<K,V> f; int n, i, fh;
//如果桶为空,初始化
if (tab == null || (n = tab.length) == 0)
tab = initTable();
else if ((f = tabAt(tab, i = (n - 1) & hash)) == null) {
//采用CAS无锁put入新的元素,成功返回
//失败自旋
if (casTabAt(tab, i, null,
new Node<K,V>(hash, key, value, null)))
break; // no lock when adding to empty bin
}
//如果当前位置的 hashcode == MOVED == -1,则需要进行扩容。
else if ((fh = f.hash) == MOVED)
tab = helpTransfer(tab, f);
else {
//如果都不满足,则利用 synchronized 锁写入数据。
V oldVal = null;
synchronized (f) {
if (tabAt(tab, i) == f) {
if (fh >= 0) {
binCount = 1;
for (Node<K,V> e = f;; ++binCount) {
K ek;
if (e.hash == hash &&
((ek = e.key) == key ||
(ek != null && key.equals(ek)))) {
oldVal = e.val;
if (!onlyIfAbsent)
e.val = value;
break;
}
Node<K,V> pred = e;
if ((e = e.next) == null) {
pred.next = new Node<K,V>(hash, key,
value, null);
break;
}
}
}
else if (f instanceof TreeBin) {
Node<K,V> p;
binCount = 2;
if ((p = ((TreeBin<K,V>)f).putTreeVal(hash, key,
value)) != null) {
oldVal = p.val;
if (!onlyIfAbsent)
p.val = value;
}
}
}
}
if (binCount != 0) {
//如果达到需要转换为红黑树的阀值 TREEIFY_THRESHOLD = 8
if (binCount >= TREEIFY_THRESHOLD)
treeifyBin(tab, i);//将链表转换为红黑树
if (oldVal != null)
return oldVal;
break;
}
}
}
addCount(1L, binCount);
return null;
}
二、 CopyOnWriteArrayList
基于Java8 了解源码实现
原理: 采用读写分离的思想实现并发访问, 而且保证读读之间在任何时候都不会被阻塞。
缺点:
- 内存占用问题
- 数据一致性问题
2.1 内部成员
//可重入锁
final transient ReentrantLock lock = new ReentrantLock();
//数组 volatile:保证可见性,
private transient volatile Object[] array;
//弱一致性的迭代器
static final class COWIterator<E> implements ListIterator<E>
// 反射机制 Unsafe类
private static final sun.misc.Unsafe UNSAFE;
// lock域的内存偏移量
private static final long lockOffset;
static {
try {
//实例化Unsafe类
UNSAFE = sun.misc.Unsafe.getUnsafe();
Class<?> k = CopyOnWriteArrayList.class;
//锁的偏移量
lockOffset = UNSAFE.objectFieldOffset
(k.getDeclaredField("lock"));
} catch (Exception e) {
throw new Error(e);
}
}
2.2 构造方法
public CopyOnWriteArrayList() {
setArray(new Object[0]); //初始化长度为0 的数组
}
public CopyOnWriteArrayList(Collection<? extends E> c) {
Object[] elements;
if (c.getClass() == CopyOnWriteArrayList.class)
elements = ((CopyOnWriteArrayList<?>)c).getArray();
else {
elements = c.toArray();
// c.toArray might (incorrectly) not return Object[] (see 6260652)
if (elements.getClass() != Object[].class)
elements = Arrays.copyOf(elements, elements.length, Object[].class);
}
setArray(elements);
}
public CopyOnWriteArrayList(E[] toCopyIn) {
setArray(Arrays.copyOf(toCopyIn, toCopyIn.length, Object[].class));
}
2.3 get方法
//volatile 修饰数组引用,保证可见性
private transient volatile Object[] array;
final Object[] getArray() {
return array;
}
public E get(int index) {
return get(getArray(), index);
}
@SuppressWarnings("unchecked")
private E get(Object[] a, int index) {
return (E) a[index]; //通过下标获取数组元素, 没有做任何加锁操作
}
2.4 add 方法
public boolean add(E e) {
final ReentrantLock lock = this.lock;
lock.lock(); //获取锁
try {
//获取原数组
Object[] elements = getArray();
int len = elements.length;
//拷贝原数组到新的新数组
Object[] newElements = Arrays.copyOf(elements, len + 1);
//操作新的数组
newElements[len] = e;
//将旧数组引用指向新的数组
setArray(newElements);
return true;
} finally {
lock.unlock(); //释放锁
}
}
三、阻塞队列BlockingQueue
原理:采用等待通知机制实现, 底层采用可重入锁和Condition实现
3.1 JDK 中的阻塞队列实现
- ArrayBlockingQueue 一个由数组结构组成的有界阻塞队列。
- LinkedBlockingQueue 一个由链表结构组成的有界阻塞队列。
- PriorityBlockingQueue 一个支持优先级排序的无界优先级阻塞队列。
- DelayQueue:一个使用优先级队列实现的无界延迟阻塞队列。
- SynchronousQueue 一个不存储元素的阻塞队列。
- LinkedTransferQueue 一个由链表结构组成的无界阻塞队列。
- LinkedBlockingDeque 一个由链表结构组成的双向阻塞队列。
3.2 对ArrayBlockingQueue 进行分析(Java8)
3.2.1 成员变量
//队列容器数组
final Object[] items;
/** items index for next take, poll, peek or remove */
int takeIndex;
/** items index for next put, offer, or add */
int putIndex;
//队列元素个数
int count;
//可重入锁
final ReentrantLock lock;
//队列条件锁(队列挂起出队列线程)
private final Condition notEmpty;
//队列条件锁(队列挂起入队列线程)
private final Condition notFull;
3.2.2 构造函数
//capacity 容量
//fair 是否公平访问队列:()
//true 在插入和删除操作中会阻塞线程,按照FIFO的顺序执行访问,
//false 线程访问顺序不确定
public ArrayBlockingQueue(int capacity, boolean fair) {
if (capacity <= 0)
throw new IllegalArgumentException();
this.items = new Object[capacity];
lock = new ReentrantLock(fair);
notEmpty = lock.newCondition();
notFull = lock.newCondition();
}
public ArrayBlockingQueue(int capacity, boolean fair,
Collection<? extends E> c) {
this(capacity, fair);
final ReentrantLock lock = this.lock;
lock.lock(); // Lock only for visibility, not mutual exclusion
try {
int i = 0;
try {
for (E e : c) {
checkNotNull(e);
items[i++] = e;
}
} catch (ArrayIndexOutOfBoundsException ex) {
throw new IllegalArgumentException();
}
count = i;
putIndex = (i == capacity) ? 0 : i;
} finally {
lock.unlock();
}
}
3.2.3 入队列
//入队列,队列已满返回false
public boolean offer(E e) {
checkNotNull(e); //检查元素是否为空
final ReentrantLock lock = this.lock;
lock.lock();//获取锁
try {
if (count == items.length) //如果队列已满,返回false
return false;
else {
enqueue(e);//添加元素到队列尾部
return true;
}
} finally {
lock.unlock();//释放锁
}
}
//入队列,已满的挂起线程等待
public void put(E e) throws InterruptedException {
checkNotNull(e);
final ReentrantLock lock = this.lock;
lock.lockInterruptibly(); //获取锁,可打断
try {
while (count == items.length) //如果队列已满,挂起线程,释放锁
notFull.await();
enqueue(e);//入队列
} finally {
lock.unlock();//释放锁
}
}
//入队列,可设置超时
public boolean offer(E e, long timeout, TimeUnit unit)
throws InterruptedException {
checkNotNull(e);
long nanos = unit.toNanos(timeout);//超时时间
final ReentrantLock lock = this.lock;
lock.lockInterruptibly();//获取锁,可打断
try {
while (count == items.length) {
if (nanos <= 0)
return false;
nanos = notFull.awaitNanos(nanos);等待超时挂起线程, 释放锁
}
enqueue(e);
return true;
} finally {
lock.unlock();
}
}
//入队列
private void enqueue(E x) {
// assert lock.getHoldCount() == 1;
// assert items[putIndex] == null;
final Object[] items = this.items;
items[putIndex] = x;
if (++putIndex == items.length)
putIndex = 0;
count++;
notEmpty.signal(); //唤醒takes线程
}
3.2.4 出队列
//出队列
public E poll() {
final ReentrantLock lock = this.lock;
lock.lock();
try {
return (count == 0) ? null : dequeue();
} finally {
lock.unlock();
}
}
public E take() throws InterruptedException {
final ReentrantLock lock = this.lock;
lock.lockInterruptibly();
try {
while (count == 0)
notEmpty.await(); //队列为空,挂起线程
return dequeue();
} finally {
lock.unlock();
}
}
//超时出队列
public E poll(long timeout, TimeUnit unit) throws InterruptedException {
long nanos = unit.toNanos(timeout);
final ReentrantLock lock = this.lock;
lock.lockInterruptibly();
try {
while (count == 0) {
if (nanos <= 0)
return null;
nanos = notEmpty.awaitNanos(nanos);//队列为空,超时挂起线程
}
return dequeue();
} finally {
lock.unlock();
}
}
//出队列具体逻辑
private E dequeue() {
// assert lock.getHoldCount() == 1;
// assert items[takeIndex] != null;
final Object[] items = this.items;
@SuppressWarnings("unchecked")
E x = (E) items[takeIndex];//获取元素
items[takeIndex] = null; //置空,帮助GC
if (++takeIndex == items.length)
takeIndex = 0;
count--;
if (itrs != null)
itrs.elementDequeued(); //通知迭代器更新状态
notFull.signal();//唤醒put线程
return x;
}
四、高效读写队列 ConcurrentLinkedQueue(未完成)
ConcurrentLinkedQueue是一个基于链接节点的无界线程安全队列,它采用先进先出的规则对节点进行排序,当我们添加一个元素的时候,它会添加到队列的尾部;当我们获取一个元素时,它会返回队列头部的元素。它采用了“wait-free”算法(即CAS算法)来实现,该算法在Michael&Scott算法上进行了一些修改。
注意:
- 该队列不支持存储空值
4.1 成员变量
//头节点
private transient volatile Node<E> head;
//尾节点
private transient volatile Node<E> tail;
//节点类
private static class Node<E> {
volatile E item;
volatile Node<E> next;
// Unsafe mechanics
private static final sun.misc.Unsafe UNSAFE;
private static final long itemOffset;
private static final long nextOffset;
static {
try {
UNSAFE = sun.misc.Unsafe.getUnsafe();
Class<?> k = Node.class;
itemOffset = UNSAFE.objectFieldOffset
(k.getDeclaredField("item"));
nextOffset = UNSAFE.objectFieldOffset
(k.getDeclaredField("next"));
} catch (Exception e) {
throw new Error(e);
}
}
}
4.2 入队列 无锁实现
public boolean offer(E e) {
checkNotNull(e);
final Node<E> newNode = new Node<E>(e);
for (Node<E> t = tail, p = t;;) {//从尾节点插入
Node<E> q = p.next;
if (q == null) { //如果p节点的后继指针为空, 则p为队列的尾节点
// p is last node
if (p.casNext(null, newNode)) {//把新节点加入队列的尾部
// Successful CAS is the linearization point
// for e to become an element of this queue,
// and for newNode to become "live".
if (p != t) // hop two nodes at a time
casTail(t, newNode); // Failure is OK.//设置尾节点
return true;
}
// Lost CAS race to another thread; re-read next
}
else if (p == q)
// We have fallen off list. If tail is unchanged, it
// will also be off-list, in which case we need to
// jump to head, from which all live nodes are always
// reachable. Else the new tail is a better bet.
p = (t != (t = tail)) ? t : head;
else
// Check for tail updates after two hops.
p = (p != t && t != (t = tail)) ? t : q;
}
}
4.3 出队列实现
public E poll() {
restartFromHead:
for (;;) {
for (Node<E> h = head, p = h, q;;) {
E item = p.item;
if (item != null && p.casItem(item, null)) {
// Successful CAS is the linearization point
// for item to be removed from this queue.
if (p != h) // hop two nodes at a time
updateHead(h, ((q = p.next) != null) ? q : p);
return item;
}
else if ((q = p.next) == null) {
updateHead(h, p);
return null;
}
else if (p == q)
continue restartFromHead;
else
p = q;
}
}
}
五、随机数据结构:跳表(SkipList)
5.1 跳跃表了解
跳跃表(skiplist)是一种随机化的数据结构, 在 1989 年由 William Pugh 在论文《Skip lists: a probabilistic alternative to balanced trees》中提出, 跳跃表以有序的方式在层次化的链表中保存元素,搜索、插入和删除的时间复杂度为O(logN)
- 图示(WiKi)
5.2 Java 实现简单的SkipList
- 定义SkipList 的节点 ```java /**
- 节点类 */ class Node { //数据域 int key; //forward 数组,用于保存不同层级的指针 Node[] forwards; //节点最大等级 int maxLevel = MAX_LEVEL; } ```
- 使用随机数算法决定新增节点的高度 ```java /**
- 定义最大层级 / private final static int MAX_LEVEL = 16; /*
- 随机选择节点作为索引的概率, 这里取50% / private final static float P = 0.5f; /*
- 随机等级算法 *
- @return 返回随机层数
*/
private int randomLevel() {
int level = 1;
while (Math.random() < P && level < MAX_LEVEL) {
} return level; } ```level++;
- 跳表的插入实现
基本思路:我们将会从跳表的最高等级开始比较当前节点(一般会定义一个头节点)的下一个节点的key 与将要插入的key
- 如果下一个节点的key 小于将要插入节点的key,继续在同一层等级中遍历下一个节点
- 如果下一个节点的key 大于将要插入节点的key, 保存当前节点i 到数组update[i] 中,向下移一个等级继续遍历
- 插入图示(WIKI)
- Java 代码实现
5.3 并发容器 ConcurrentSkipListMap
参考
- https://crossoverjie.top/2018/07/23/java-senior/ConcurrentHashMap/
- Java 并发编程的艺术
- https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/CopyOnWriteArrayList.html
- http://ifeve.com/java-copy-on-write/
- https://juejin.im/post/5aeeb55f5188256715478c21
- concurrentlinkedqueue原理探究
- https://blog.csdn.net/qq_38293564/article/details/80798310
- https://zhuanlan.zhihu.com/p/53975333
- https://github.com/wangzheng0822/algo/blob/master/java/17_skiplist/SkipList.java
- https://blog.csdn.net/bohu83/article/details/83654524
- https://www.geeksforgeeks.org/skip-list-set-2-insertion/