添加了部分CopyOnWriteArrayList的简介

This commit is contained in:
xiangflight 2018-07-12 14:51:39 +08:00
parent c9718335fa
commit 906e58ef7c
2 changed files with 25 additions and 0 deletions

BIN
.DS_Store vendored Normal file

Binary file not shown.

View File

@ -255,6 +255,31 @@ List<String> synList = Collections.synchronizedList(list);
List<String> list = new CopyOnWriteArrayList<>();
```
扩展CopyOnWriteArrayList是一种CopyOnWrite容器即写时复制的容器。从以下源码中看出当向容器中添加元素时不是直接往当前容器添加而是Copy当前容器在新容器中添加添加完后将原容器的引用指向新容器。这样做可以对CopyOnWrite容器进行并发的读不需要加锁极大地提高了读性能因此适用于读多写少的场景。
```java
public boolean add(E e) {
final ReentrantLock lock = this.lock;
lock.lock();
try {
Object[] elements = getArray();
int len = elements.length;
Object[] newElements = Arrays.copyOf(elements, len + 1); // 复制到新容器
newElements[len] = e;
setArray(newElements);
return true;
} finally {
lock.unlock();
}
}
@SuppressWarnings("unchecked")
private E get(Object[] a, int index) {
return (E) a[index];
}
```
## LinkedList
### 1. 概览