CopyOnWriteSet
看了下CopyOnWriteSet源码,底层使用的是CopyOnWriteList,根据底层的实现,每次读取都是N的复杂度.每次写也是N的复杂度.有个代码可以看一下,
来自CopyOnWriteList
public boolean addIfAbsent(E e) {
Object[] snapshot = getArray();
return indexOf(e, snapshot, , snapshot.length) >= ? false :
addIfAbsent(e, snapshot);
}
private boolean addIfAbsent(E e, Object[] snapshot) {
final ReentrantLock lock = this.lock;
lock.lock();
try {
Object[] current = getArray();
int len = current.length;
if (snapshot != current) {
// Optimize for lost race to another addXXX operation
int common = Math.min(snapshot.length, len);
for (int i = ; i < common; i++)
if (current[i] != snapshot[i] && eq(e, current[i]))
return false;
if (indexOf(e, current, common, len) >= )
return false;
}
Object[] newElements = Arrays.copyOf(current, len + );
newElements[len] = e;
setArray(newElements);
return true;
} finally {
lock.unlock();
}
}
代码的逻辑如下,获取数组snapshot,执行indexOf,如果没有,准备把新元素加入进去.
在实际加入方法内,获取锁,获取最新的数组current,如果俩个指针还是同一个指针,那就是没有改变,要不然.
取来个数组长度的最小值.
对current里面获取改变后的元素执行eq方法.对未比较过的元素执行indexof方法.要是还是没有重复的方法,就加入e