CopyOnWriteArraySet
CopyOnWriteArraySet是一个线程安全的HashSet.但是它们的实现并不相同。HashSet是基于散列列表实现的。而CopyOnWriteArraySet的底层实际上是一个CopyOnWriteArrayList.也就是说基于动态数组实现。
在其保证线程安全上跟CopyOnWriteArrayList的机制是一样的。但是因为set集合是不允许重复的。而list集合是允许重复的。所以CopyOnWriteArrayList额外提供了addIfAbsent()和addAllAbsent()这两个添加元素的API,通过这些API来添加元素时,只有当元素不存在时才执行添加操作!
/**
* Append the element if not present.
*
* @param e element to be added to this list, if absent
* @return <tt>true</tt> if the element was added
*/
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();
}
}
如果这个元素已经存在就返回false退出。如果不存在就添加。
注意在CopyOnWriteArraySet与CopyOnWriteArrayList用iterator迭代器进行迭代的时候,是不支持remove操作的。
/**
* Not supported. Always throws UnsupportedOperationException.
* @throws UnsupportedOperationException always; <tt>remove</tt>
* is not supported by this iterator.
*/
public void remove() {
throw new UnsupportedOperationException();
}
其它原理都与CopyOnWriteArrayList基本一致。所以不再对CopyOnWriteArraySet的代码进行详细的解析了。若对CopyOnWriteArrayList不了解,可以阅读http://blog.csdn.net/pengdandezhi/article/details/68958338