以下是来自 ConcurrentWeakKeyHashMap.java 的 isEmpty() 方法, https://github.com/netty/netty/blob/master/src/main/java/org/jboss/netty/util/internal/ConcurrentWeakKeyHashMap.java
为什么它需要 mcsum,if(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,而另一个线程持续添加/删除相同的密钥对值