File tree Expand file tree Collapse file tree 2 files changed +25
-0
lines changed
Expand file tree Collapse file tree 2 files changed +25
-0
lines changed Original file line number Diff line number Diff line change @@ -255,6 +255,31 @@ List<String> synList = Collections.synchronizedList(list);
255255List<String > list = new CopyOnWriteArrayList<> ();
256256```
257257
258+ 扩展:CopyOnWriteArrayList是一种CopyOnWrite容器,即写时复制的容器。从以下源码中看出:当向容器中添加元素时,不是直接往当前容器添加,而是Copy当前容器,在新容器中添加,添加完后,将原容器的引用指向新容器。这样做可以对CopyOnWrite容器进行并发的读,不需要加锁,极大地提高了读性能,因此适用于读多写少的场景。
259+
260+ ``` java
261+ public boolean add(E e) {
262+ final ReentrantLock lock = this . lock;
263+ lock. lock();
264+ try {
265+ Object [] elements = getArray();
266+ int len = elements. length;
267+ Object [] newElements = Arrays . copyOf(elements, len + 1 ); // 复制到新容器
268+ newElements[len] = e;
269+ setArray(newElements);
270+ return true ;
271+ } finally {
272+ lock. unlock();
273+ }
274+ }
275+
276+ @SuppressWarnings (" unchecked" )
277+ private E get(Object [] a, int index) {
278+ return (E ) a[index];
279+ }
280+
281+ ```
282+
258283## LinkedList
259284
260285### 1. 概览
You can’t perform that action at this time.
0 commit comments