從ConcurrentWeakKeyHashMap.java以下是的isEmpty()方法, https://github.com/netty/netty/blob/master/src/main/java/org/jboss/netty/util/internal/ConcurrentWeakKeyHashMap.javaConcurrentWeakKeyHashMap的isEmpty方法
爲什麼它需要mcsum,又是什麼的,如果(mcsum!= 0){..}塊在做什麼?
更重要的是,我怎麼
if (segments[i].count != 0 || mc[i] != segments[i].modCount)
評估爲真?
public boolean isEmpty() {
final Segment<K, V>[] segments = this.segments;
/*
* We keep track of per-segment modCounts to avoid ABA problems in which
* an element in one segment was added and in another removed during
* traversal, in which case the table was never actually empty at any
* point. Note the similar use of modCounts in the size() and
* containsValue() methods, which are the only other methods also
* susceptible to ABA problems.
*/
int[] mc = new int[segments.length];
int mcsum = 0;
for (int i = 0; i < segments.length; ++ i) {
if (segments[i].count != 0) {
return false;
} else {
mcsum += mc[i] = segments[i].modCount;
}
}
// If mcsum happens to be zero, then we know we got a snapshot before
// any modifications at all were made. This is probably common enough
// to bother tracking.
if (mcsum != 0) {
for (int i = 0; i < segments.length; ++ i) {
if (segments[i].count != 0 || mc[i] != segments[i].modCount) {
return false;
}
}
}
return true;
}
編輯: 代碼以評價以上如果塊現在處於ConcurrentWeakKeyHashMapTest
本質1個螺紋汽車無監視concurrentMap,而另一個線程連續添加/刪除相同密鑰對值
感謝您的詳細解答。現在我只需要提供一個java代碼來測試上面的內容,試圖將上面的if塊評估爲true – portoalet
對於這個塊來說,它實際上很簡單:只需將一個元素插入到正在檢查的段中即可。 –
要測試的代碼位於:https://github.com/lydonchandra/netty/blob/master/src/test/java/org/jboss/netty/util/internal/ConcurrentWeakKeyHashMapTest.java – portoalet