JUC包下的CopyOnWriteArraySet集合

CopyOnWriteArraySet
CopyOnWriteArraySet在CopyOnWriteArrayList基础上进行实现的,主要区别于set是去重的集合,所以再添加方法上略有不一样;
//继承与AbstractSet
public class CopyOnWriteArraySet<E> extends AbstractSet<E> implements java.io.Serializable //聚合 private final CopyOnWriteArrayList<E> al; //主要介绍add方法 public boolean add(E e) {
        return al.addIfAbsent(e);//调用CopyOnWriteArrayList的方法进行添加
    }

//主要实现由此方法
 public boolean addIfAbsent(E e) {
     Object[] snapshot = getArray();
     //要添加的元素e,由snapshot数组的0-最后一位进行遍历查找,是否包含元素e,不包含的情况下插入元素e
     return indexOf(e, snapshot, 0, snapshot.length) >= 0 ? false :
         addIfAbsent(e, snapshot);
 }

//判断一个数组中是否包含某一个元素
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;
}

//添加元素时进行上锁,避免多线程情况下出现错误数据
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);
        return true;
    } finally {
        lock.unlock();
    }
}
    原文作者:JUC
    原文地址: https://blog.csdn.net/qq_35241080/article/details/82529303
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞