On CopyOnWriteArraySet

FIG CopyOnWriteArraySet structure
 
CopyOnWriteArraySet.png
CopyOnWriteArraySet main method
  • public boolean add(E e);
  • public boolean remove(Object o);
CopyOnWriteArraySet main method of interpretation

Look at public boolean add (E e) source

 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(); } } 

Look at public boolean remove (Object o) Source

  public boolean remove(Object o){ return al.remove(o); } //调用CopyOnWriteArrayList的删除 
CopyOnWriteArraySet traverse introduction

The common way to navigate:

       //one  foreach  遍历
        for (Object o : list) {
            System.out.println(o);
        }
        //two 迭代器的遍历
        Iterator iterator = list.iterator();
        while (iterator.hasNext()){
            System.out.println(iterator.next());
        }
Other features introduced CopyOnWriteArraySet
  • First, what is the data structure CopyOnWriteArraySet? In fact, its structure is a set of strict sense, it's the underlying implementation is to use an array, its implementation is the upper CopyOnWriteArrayList.
  • Secondly, CopyOnWriteArraySet is a collection, so it is not repeated placement elements, it is logical to take the weight reflected in the add.
  • Finally, CopyOnWriteArraySet using CopyOnWriteArrayList to achieve, because CopyOnWriteArrayList is thread-safe, so CopyOnWriteArraySet operation is also thread-safe.

Guess you like

Origin www.cnblogs.com/exmyth/p/11588440.html