CopyOnWriteArraySet结构图
image.pngCopyOnWriteArraySet主要方法
public boolean add(E e);
public boolean remove(Object o);
CopyOnWriteArraySet解读主要方法
来看一下public boolean add(E e)源码
public boolean add(E e) {
//这个al就是CopyOnWriteArrayList也就是说CopyOnWriteArraySet内部是用CopyOnWriteArrayList来实现的
return al.addIfAbsent(e);
}
//这段代码也很好理解就是首先检查原来的数组里面有没有要添加的元素,如果有的话就不要再添加了,如果没有的话,创建一个新的数组,复制之前数组元素并且添加新的元素
public boolean addIfAbsent(E e) {
final ReentrantLock lock = this.lock;
lock.lock();
try {
// Copy while checking if already present.
// This wins in the most common case where it is not present
Object[] elements = getArray();
int len = elements.length;
Object[] newElements = new Object[len + 1];
for (int i = 0; i < len; ++i) {
if (eq(e, elements[i]))
return false; // exit, throwing away copy
else
newElements[i] = elements[i];
}
newElements[len] = e;
setArray(newElements);
return true;
} finally {
lock.unlock();
}
}
来看一下 public boolean remove(Object o)源码
public boolean remove(Object o){
return al.remove(o);
}
//调用CopyOnWriteArrayList的删除
总结
(1)CopyOnWriteArraySet是用CopyOnWriteArrayList实现的;
(2)CopyOnWriteArraySet是有序的,因为底层其实是数组,数组是不是有序的?!
(3)CopyOnWriteArraySet是并发安全的,而且实现了读写分离;
(4)CopyOnWriteArraySet通过调用CopyOnWriteArrayList的addIfAbsent()方法来保证元素不重复;
网友评论