线程安全的Set,底层使用CopyOnWriteArrayList实现
唯一不同在于,使用addIfAbsent()添加元素,会遍历数组
如存在元素,则不添加(扔掉副本)
Set<String> set = new CopyOnWriteArraySet<String>();
底层实现过程:
第一步:调用调用CopyOnWriteArrayList下的addIfAbsent()方法
public boolean add(E e) {
return al.addIfAbsent(e);
}//调用CopyOnWriteArrayList下的addIfAbsent()方法
第二步:调用判断方法
public boolean addIfAbsent(E e) {
Object[] snapshot = getArray();//e插入的值,snapshot数组
return indexOf(e, snapshot, 0, snapshot.length) >= 0 ? false :
addIfAbsent(e, snapshot);//第四步的操作
}//调用indexOf()方法如果存在返回false,如果不存在返回新建的数组。
第三步:判断过程
//判断过程
private static int indexOf(Object o, Object[] elements,
int index, int fence) {
if (o == null) {
for (int i = index; i < fence; i++)
if (elements[i] == null)
return i;
} else {
for (int i = index; i < fence; i++)
if (o.equals(elements[i]))
return i;
}
return -1;//表示没有相同元素
}
第四步:Lock锁更安全,扩容数组
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 = 0; i < common; i++)
if (current[i] != snapshot[i] && eq(e, current[i]))
return false;
if (indexOf(e, current, common, len) >= 0)
return false;
}
Object[] newElements = Arrays.copyOf(current, len + 1);
newElements[len] = e;
setArray(newElements);//和CopyOnWroteArrayList相同
return true;
} finally {
lock.unlock();//释放锁
}
}