CopyOnWriteArrayList copy-on-write idea

Copy-on-write

The conpyOnWrite container is a copy-on-write container. When adding elements to a container, instead of directly adding to the current container Object [], the current container Object [] is first copied, and a new container Object [] newElements is copied, then Add elements to the new container newElements. After adding the elements, talk about the reference of the meta container to the new container setArray (newElements). The advantage of this is that the copyOnWrite container can be read concurrently without locking, because The current container will not add any elements. So copyOnWrite is also a separate idea of ​​reading and writing, reading and writing different containers.

 1  public boolean add(E e) {
 2         final ReentrantLock lock = this.lock;
 3         lock.lock();
 4         try {
 5             Object[] elements = getArray();
 6             int len = elements.length;
 7             Object[] newElements = Arrays.copyOf(elements, len + 1);
 8             newElements[len] = e;
 9             setArray(newElements);
10             return true;
11         } finally {
12             lock.unlock();
13         }
14     }

 

Guess you like

Origin www.cnblogs.com/max-home/p/12722347.html