添加了部分CopyOnWriteArrayList的简介
This commit is contained in:
parent
c9718335fa
commit
906e58ef7c
|
@ -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. 概览
|
||||
|
|
Loading…
Reference in New Issue
Block a user