讀ConcurrentSkipListMap源碼


//數據結構是跳錶 關於數據結構http://blog.csdn.net/coslay/article/details/44819823這篇文章寫得很好
//另外ConcurrentSkipListSet底層也是用ConcurrentSkipListMap實現的。
//先看構造函數
public ConcurrentSkipListMap() {
this.comparator = null;
initialize();
}

public ConcurrentSkipListMap(Comparator<? super K> comparator) {
this.comparator = comparator;
initialize();
}

public ConcurrentSkipListMap(Map<? extends K, ? extends V> m) {
this.comparator = null;
initialize();
putAll(m);
}
public void putAll(Map<? extends K, ? extends V> m) {
for (Map.Entry<? extends K, ? extends V> e : m.entrySet())
put(e.getKey(), e.getValue());
}
public ConcurrentSkipListMap(SortedMap<K, ? extends V> m) {
this.comparator = m.comparator();
initialize();
buildFromSorted(m);
}
final void initialize() {
keySet = null;
entrySet = null;
values = null;
descendingMap = null;
randomSeed = seedGenerator.nextInt() | 0x0100; // ensure nonzero
//初始化頭節點
head = new HeadIndex<K,V>(new Node<K,V>(null, BASE_HEADER, null),
null, null, 1);
}

private void buildFromSorted(SortedMap<K, ? extends V> map) {
if (map == null)
throw new NullPointerException();

HeadIndex<K,V> h = head;
Node<K,V> basepred = h.node;

ArrayList<Index<K,V>> preds = new ArrayList<Index<K,V>>();

// 初始化
for (int i = 0; i <= h.level; ++i)
preds.add(null);
Index<K,V> q = h;
for (int i = h.level; i > 0; --i) {
preds.set(i, q);
q = q.down;
}

Iterator<? extends Map.Entry<? extends K, ? extends V>> it =
map.entrySet().iterator();
while (it.hasNext()) {
Map.Entry<? extends K, ? extends V> e = it.next();
int j = randomLevel();
if (j > h.level) j = h.level + 1;
K k = e.getKey();
V v = e.getValue();
if (k == null || v == null)
throw new NullPointerException();
Node<K,V> z = new Node<K,V>(k, v, null);
basepred.next = z;
basepred = z;
if (j > 0) {
Index<K,V> idx = null;
for (int i = 1; i <= j; ++i) {
idx = new Index<K,V>(z, idx, null);
if (i > h.level)
h = new HeadIndex<K,V>(h.node, h, idx, i);

if (i < preds.size()) {
preds.get(i).right = idx;
preds.set(i, idx);
} else
preds.add(idx);
}
}
}
head = h;
}
//新增元素
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);
for (;;) {
//找到前驅節點
Node<K,V> b = findPredecessor(key);
//拿到下一個節點
Node<K,V> n = b.next;
//插入到b n之間,循環找到n
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;
}
//b被刪除了
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);
//設置不成功則繼續循環
if (!b.casNext(n, z))
break; // restart if lost race to append to b
//隨機計算一個層級
int level = randomLevel();

if (level > 0)
//將z插入到該層級
insertIndex(z, level);
return null;
}
}
}

private Comparable<? super K> comparable(Object key)
throws ClassCastException {
if (key == null)
throw new NullPointerException();
if (comparator != null)
return new ComparableUsingComparator<K>((K)key, comparator);
else
return (Comparable<? super K>)key;
}

static final class ComparableUsingComparator<K> implements Comparable<K> {
final K actualKey;
final Comparator<? super K> cmp;
ComparableUsingComparator(K key, Comparator<? super K> cmp) {
this.actualKey = key;
this.cmp = cmp;
}
public int compareTo(K k2) {
return cmp.compare(actualKey, k2);
}
}

//找到前驅節點
private Node<K,V> findPredecessor(Comparable<? super K> key) {
if (key == null)
throw new NullPointerException(); // don't postpone errors
//先橫着找
for (;;) {
Index<K,V> q = head;
Index<K,V> r = q.right;
for (;;) {
//右邊還有節點
if (r != null) {
Node<K,V> n = r.node;
K k = n.key;
//如果節點的值爲null刪掉該節點
if (n.value == null) {
//刪除失敗重新橫着找
if (!q.unlink(r))
break; // restart
//成功接着橫着找
r = q.right; // reread r
continue;
}
//如果key比當前節點大繼續找
if (key.compareTo(k) > 0) {
q = r;
r = r.right;
continue;
}
}
//橫着找完了往下一級找
Index<K,V> d = q.down;
if (d != null) {
q = d;
r = d.right;
} else
return q.node;
}
}
}

final boolean unlink(Index<K,V> succ) {
return !indexesDeletedNode() && casRight(succ, succ.right);
}

final boolean indexesDeletedNode() {
return node.value == null;
}

final boolean casRight(Index<K,V> cmp, Index<K,V> val) {
return UNSAFE.compareAndSwapObject(this, rightOffset, cmp, val);
}

//插入到層級中
private void insertIndex(Node<K,V> z, int level) {
HeadIndex<K,V> h = head;
int max = h.level;
//如果小於當前的最大層級
if (level <= max) {
Index<K,V> idx = null;
for (int i = 1; i <= level; ++i)
idx = new Index<K,V>(z, idx, null);
addIndex(idx, h, level);

} else {
//新增層級
level = max + 1;
Index<K,V>[] idxs = (Index<K,V>[])new Index[level+1];
Index<K,V> idx = null;
for (int i = 1; i <= level; ++i)
idxs[i] = idx = new Index<K,V>(z, idx, null);

HeadIndex<K,V> oldh;
int k;
for (;;) {
oldh = head;
int oldLevel = oldh.level;
//其他線程新增了層級
if (level <= oldLevel) { // lost race to add level
k = level;
break;
}
HeadIndex<K,V> newh = oldh;
Node<K,V> oldbase = oldh.node;
for (int j = oldLevel+1; j <= level; ++j)
newh = new HeadIndex<K,V>(oldbase, newh, idxs[j], j);
//設置頭
if (casHead(oldh, newh)) {
k = oldLevel;
break;
}
}
addIndex(idxs[k], oldh, k);
}
}

//插入到層級
private void addIndex(Index<K,V> idx, HeadIndex<K,V> h, int indexLevel) {
int insertionLevel = indexLevel;
Comparable<? super K> key = comparable(idx.node.key);
if (key == null) throw new NullPointerException();

// Similar to findPredecessor, but adding index nodes along
// path to key.
for (;;) {
int j = h.level;
Index<K,V> q = h;
Index<K,V> r = q.right;
Index<K,V> t = idx;
for (;;) {
if (r != null) {
Node<K,V> n = r.node;
// compare before deletion check avoids needing recheck
int c = key.compareTo(n.key);

if (n.value == null) {
//移除r
if (!q.unlink(r))
break;
r = q.right;
繼續循環
continue;
}
//如果比他大繼續循環
if (c > 0) {
q = r;
r = r.right;
continue;
}
}
//如果剛好在插入的層級
if (j == insertionLevel) {
//t的node value值爲null t是要被刪除的節點所以不插入
if (t.indexesDeletedNode()) {
//尋找節點並且刪除其中的null節點
findNode(key); // cleans up
return;
}
//插入新節點失敗
if (!q.link(r, t))
break; // restart
//如果現在是最底層了
if (--insertionLevel == 0) {
// need final deletion check before return
if (t.indexesDeletedNode())
findNode(key);
return;
}
}
//當--insertionLevel後如果滿足,說明該層需要插入節點
if (--j >= insertionLevel && j < indexLevel)
t = t.down;
q = q.down;
r = q.right;
}
}
}

//尋找相等節點並且移除空節點
private Node<K,V> findNode(Comparable<? super K> key) {
for (;;) {
Node<K,V> b = findPredecessor(key);
Node<K,V> n = b.next;
for (;;) {
if (n == null)
return null;
Node<K,V> f = n.next;
//n變了說明其他線程操作過了
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)
return n;
if (c < 0)
return null;
b = n;
n = f;
}
}
}


//刪除節點
void helpDelete(Node<K,V> b, Node<K,V> f) {

if (f == next && this == b.next) {
//說明f已經被修改
if (f == null || f.value != f) // not already marked
appendMarker(f);
else
b.casNext(this, f.next);
}
}


boolean appendMarker(Node<K,V> f) {
return casNext(f, new Node<K,V>(f));
}

//在node與succ之間插入新節點
final boolean link(Index<K,V> succ, Index<K,V> newSucc) {
Node<K,V> n = node;
newSucc.right = succ;
return n.value != null && casRight(succ, newSucc);
}

//刪除某個節點
public V remove(Object key) {
return doRemove(key, null);
}


final V doRemove(Object okey, Object value) {
Comparable<? super K> key = comparable(okey);
for (;;) {
//找到前一個節點
Node<K,V> b = findPredecessor(key);
Node<K,V> n = b.next;
for (;;) {
if (n == null)
return 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);
//找完了都沒有找到返回null
if (c < 0)
return null;
//繼續找
if (c > 0) {
b = n;
n = f;
continue;
}
//如果value不相等返回null
if (value != null && !value.equals(v))
return null;
//設置null失敗重新循環
if (!n.casValue(v, null))
break;
//添加刪除標記
if (!n.appendMarker(f) || !b.casNext(n, f))
findNode(key); // Retry via findNode
else {
//刪除節點
findPredecessor(key); // Clean index
//最頂層的節點刪完了嘗試降低層級
if (head.right == null)
tryReduceLevel();
}
return (V)v;
}
}
}

private void tryReduceLevel() {
HeadIndex<K,V> h = head;
HeadIndex<K,V> d;
HeadIndex<K,V> e;
if (h.level > 3 &&
(d = (HeadIndex<K,V>)h.down) != null &&
(e = (HeadIndex<K,V>)d.down) != null &&
e.right == null &&
d.right == null &&
h.right == null &&
casHead(h, d) && // try to set
h.right != null) // recheck
casHead(d, h); // try to backout
}

//只有key不在列表中時才設置值
public V putIfAbsent(K key, V value) {
if (value == null)
throw new NullPointerException();
return doPut(key, value, true);
}

//根據key獲取值
public V get(Object key) {
return doGet(key);
}

private V doGet(Object okey) {
Comparable<? super K> key = comparable(okey);

for (;;) {
Node<K,V> n = findNode(key);
if (n == null)
return null;
Object v = n.value;
if (v != null)
return (V)v;
}
}

//根據key和value值刪除
public boolean remove(Object key, Object value) {
if (key == null)
throw new NullPointerException();
if (value == null)
return false;
return doRemove(key, value) != null;
}

//根據key替換值
public V replace(K key, V value) {
if (value == null)
throw new NullPointerException();
Comparable<? super K> k = comparable(key);
for (;;) {
Node<K,V> n = findNode(k);
if (n == null)
return null;
Object v = n.value;
if (v != null && n.casValue(v, value))
return (V)v;
}
}


//只有和期望的值相等時才刪除
public boolean replace(K key, V oldValue, V newValue) {
if (oldValue == null || newValue == null)
throw new NullPointerException();
Comparable<? super K> k = comparable(key);
for (;;) {
Node<K,V> n = findNode(k);
if (n == null)
return false;
Object v = n.value;
if (v != null) {
if (!oldValue.equals(v))
return false;
//嘗試成功返回true,失敗接着嘗試
if (n.casValue(v, newValue))
return true;
}
}
}


//是否包含某個鍵
public boolean containsKey(Object key) {
return doGet(key) != null;
}

//是否包含某個值
public boolean containsValue(Object value) {
if (value == null)
throw new NullPointerException();
for (Node<K,V> n = findFirst(); n != null; n = n.next) {
V v = n.getValidValue();
if (v != null && value.equals(v))
return true;
}
return false;
}

//找到頭幾點的下一個節點也就是第一個節點
Node<K,V> findFirst() {
for (;;) {
Node<K,V> b = head.node;
Node<K,V> n = b.next;
if (n == null)
return null;
if (n.value != null)
return n;
//n.value==null
n.helpDelete(b, n.next);
}
}

V getValidValue() {
Object v = value;
if (v == this || v == BASE_HEADER)
return null;
return (V)v;
}

//獲取長度
public int size() {
long count = 0;
for (Node<K,V> n = findFirst(); n != null; n = n.next) {
if (n.getValidValue() != null)
++count;
}
return (count >= Integer.MAX_VALUE) ? Integer.MAX_VALUE : (int) count;
}

//隊列是否爲空
public boolean isEmpty() {
return findFirst() == null;
}

//清空隊列
public void clear() {
initialize();
}

//返回第一個key
public K firstKey() {
Node<K,V> n = findFirst();
if (n == null)
throw new NoSuchElementException();
return n.key;
}

//獲取最後一個node
Node<K,V> findLast() {

Index<K,V> q = head;
for (;;) {
Index<K,V> d, r;
//如果右邊有元素
if ((r = q.right) != null) {
//該元素是否需要被刪除
if (r.indexesDeletedNode()) {
q.unlink(r);
//重新循環
q = head; // restart
}
else
//將r賦值q繼續循環
q = r;
//循環到下一層級
} else if ((d = q.down) != null) {
q = d;
} else {
//最底層了
Node<K,V> b = q.node;
Node<K,V> n = b.next;
for (;;) {
if (n == null)
return b.isBaseHeader() ? null : b;
Node<K,V> f = n.next; // inconsistent read
if (n != b.next)
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;
b = n;
n = f;
}
q = head; // restart
}
}
}

//是否是頭幾點包含的元素
boolean isBaseHeader() {
return value == BASE_HEADER;
}

//獲取最後一個node的key值
public K lastKey() {
Node<K,V> n = findLast();
if (n == null)
throw new NoSuchElementException();
return n.key;
}

//返回小於當前key的entry值
public Map.Entry<K,V> lowerEntry(K key) {
return getNear(key, LT);
}


AbstractMap.SimpleImmutableEntry<K,V> getNear(K key, int rel) {
for (;;) {
//找到最相等的那個節點
Node<K,V> n = findNear(key, rel);
if (n == null)
return null;
AbstractMap.SimpleImmutableEntry<K,V> e = n.createSnapshot();
if (e != null)
return e;
}
}

Node<K,V> findNear(K kkey, int rel) {
Comparable<? super K> key = comparable(kkey);
for (;;) {
Node<K,V> b = findPredecessor(key);
Node<K,V> n = b.next;
for (;;) {
//b的後面沒了
if (n == null)
return ((rel & LT) == 0 || b.isBaseHeader()) ? null : b;
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 && (rel & EQ) != 0) ||
(c < 0 && (rel & LT) == 0))
return n;
if ( c <= 0 && (rel & LT) != 0)
return b.isBaseHeader() ? null : b;
b = n;
n = f;
}
}
}

AbstractMap.SimpleImmutableEntry<K,V> createSnapshot() {
V v = getValidValue();
if (v == null)
return null;
return new AbstractMap.SimpleImmutableEntry<K,V>(key, v);
}

//返回小於當前key的key值
public K lowerKey(K key) {
Node<K,V> n = findNear(key, LT);
return (n == null) ? null : n.key;
}

//返回小於或等於當前key的entry
public Map.Entry<K,V> floorEntry(K key) {
return getNear(key, LT|EQ);
}
//返回小於或等於當前key的key
public K floorKey(K key) {
Node<K,V> n = findNear(key, LT|EQ);
return (n == null) ? null : n.key;
}
//返回大於或等於當前key的entry
public Map.Entry<K,V> ceilingEntry(K key) {
return getNear(key, GT|EQ);
}
//返回大於或等於當前key的key值
public K ceilingKey(K key) {
Node<K,V> n = findNear(key, GT|EQ);
return (n == null) ? null : n.key;
}

//返回大於當前key的entry
public Map.Entry<K,V> higherEntry(K key) {
return getNear(key, GT);
}
//返回大於當前key的key值
public K higherKey(K key) {
Node<K,V> n = findNear(key, GT);
return (n == null) ? null : n.key;
}

//獲取並移除第一個entry
public Map.Entry<K,V> pollFirstEntry() {
return doRemoveFirstEntry();
}

Map.Entry<K,V> doRemoveFirstEntry() {
for (;;) {
Node<K,V> b = head.node;
Node<K,V> n = b.next;
if (n == null)
return null;
Node<K,V> f = n.next;
if (n != b.next)
continue;
Object v = n.value;
if (v == null) {
n.helpDelete(b, f);
continue;
}
//cas將值設置爲null
if (!n.casValue(v, null))
continue;
if (!n.appendMarker(f) || !b.casNext(n, f))
findFirst(); // retry
clearIndexToFirst();
return new AbstractMap.SimpleImmutableEntry<K,V>(n.key, (V)v);
}
}

private void clearIndexToFirst() {
for (;;) {
Index<K,V> q = head;
for (;;) {
Index<K,V> r = q.right;
if (r != null && r.indexesDeletedNode() && !q.unlink(r))
break;
//嘗試降級
if ((q = q.down) == null) {
if (head.right == null)
tryReduceLevel();
return;
}
}
}
}

//獲取並移除最後一個entry
public Map.Entry<K,V> pollLastEntry() {
return doRemoveLastEntry();
}

Map.Entry<K,V> doRemoveLastEntry() {
for (;;) {
//找到最後一個節點
Node<K,V> b = findPredecessorOfLast();
Node<K,V> n = b.next;
if (n == null) {
if (b.isBaseHeader()) // empty
return null;
else
continue; // all b's successors are deleted; retry
}
for (;;) {
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;
if (f != null) {
b = n;
n = f;
continue;
}
if (!n.casValue(v, null))
break;
K key = n.key;
Comparable<? super K> ck = comparable(key);
if (!n.appendMarker(f) || !b.casNext(n, f))
findNode(ck); // Retry via findNode
else {
findPredecessor(ck); // Clean index
if (head.right == null)
tryReduceLevel();
}
return new AbstractMap.SimpleImmutableEntry<K,V>(key, (V)v);
}
}
}


private Node<K,V> findPredecessorOfLast() {
for (;;) {
Index<K,V> q = head;
for (;;) {
Index<K,V> d, r;
if ((r = q.right) != null) {
if (r.indexesDeletedNode()) {
q.unlink(r);
break; // must restart
}
// proceed as far across as possible without overshooting
if (r.node.next != null) {
q = r;
continue;
}
}
if ((d = q.down) != null)
q = d;
else
return q.node;
}
}
}
//將值封裝到集合
public Collection<V> values() {
Values vs = values;
return (vs != null) ? vs : (values = new Values(this));
}


發佈了149 篇原創文章 · 獲贊 1 · 訪問量 1萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章