一个项目用到ConcurrentSkipListSet.add(E e)方法,过程中总觉得元素添加数量有问题,故调试之。
查看add()方法的javadoc,其注释为:
如果此 set 中不包含指定元素,则添加指定元素。更确切地讲,如果此 set 不包含满足 e.equals(e2) 的元素
e2,则向 set 中添加指定的元素 e。如果此 set 已经包含该元素,则调用不更改该 set 并返回
false。
根据注释,只要元素的equals()方法判断不相等就能加入到Set中,可调试发现不是这么回事:
public boolean add(E e) {
return m.putIfAbsent(e, Boolean.TRUE) == null;
}
m为 ConcurrentSkipListMap,它的putIfAbsent()方法实现是:
public V putIfAbsent(K key, V value) {
if (value == null)
throw new NullPointerException();
return doPut(key, value, true);
}
private V doPut(K kkey, V value, boolean onlyIfAbsent) {
Comparable super K> key = comparable(kkey);
for (;;) {
Node b = findPredecessor(key);
Node n = b.next;
for (;;) {
if (n != null) {
Node 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 z = new Node(kkey, value, n);
if (!b.casNext(n, z))
break; // restart if lost race to append to b
int level = randomLevel();
if (level > 0)
insertIndex(z, level);
return null;
}
}
}
实际上Set中的添加是根据元素的compareTo()方法在比较!如果compareTo()返回0,就认为2个元素相等,跟equals()方法根本没有关系!JAVA SDK 的JavaDoc也不靠谱啊~~
分享到:
相关推荐
ConcurrentSkipListSet 是Java中的一个线程安全的有序集合类,它基于跳表(Skip List)数据结构实现。 下面是关于 ConcurrentSkipListSet 的一些重要信息: 线程安全性:ConcurrentSkipListSet 是线程安全的,可以...
主要为大家详细介绍了Java concurrency集合之ConcurrentSkipListSet的相关资料,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
public static char[] chars = {'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q'} ; 比较对象 List接口 AttributeList , ArrayList , CopyOnWriteArrayList , LinkedList RoleList , ...
2.HashSet,TreeSet -- CopyONWriteArraySet,ConcurrentSkipListSet 3.hashMap , treeMap -- ConcurrentHashMap,ConcurentSkipListMap(key有序,支持更高并发) ## Concurrent同步工具类 countDownLatch ...
ConcurrentSkipListSet 替代同步的SortedSet Java 5 Java 6 同步工具类 闭锁 *应用场景 (1)确保某个计算在其需要的所有资源都被初始化后才能继续执行 (2)确保某个服务...
第一章 线程基础、线程之间...1. ConcurrentSkipListMap和ConcurrentSkipListSet: 60 2. 写时复制容器 60 五、阻塞队列 60 第五章 JMH性能测试 62 1、 JMH环境搭建 62 2、 执行 63 3、 基本概念 63 4、 注解与选项 63
线程安全set:ConcurrentSkipListSet、CopyOnWriteArraySet、ConcurrentHashMap.newKeySet()、Collections.synchronizedSet(set) 分布式技术 缓存穿透: 请求去查询缓存数据库中根本就不存在的数据。解决方案: 缓存...