Merge pull request #321 from xiangflight/master

CopyOnWriteArrayList简介
This commit is contained in:
郑永川 2018-07-12 22:07:45 +08:00 committed by GitHub
commit 67fc67e1fa
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 30 additions and 0 deletions

1
.gitignore vendored
View File

@ -0,0 +1 @@
.DS_Store

View File

@ -255,6 +255,35 @@ List<String> synList = Collections.synchronizedList(list);
List<String> list = new CopyOnWriteArrayList<>(); List<String> list = new CopyOnWriteArrayList<>();
``` ```
CopyOnWriteArrayList是一种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();
}
}
final void setArray(Object[] a) {
array = a;
}
@SuppressWarnings("unchecked")
private E get(Object[] a, int index) {
return (E) a[index];
}
```
## LinkedList ## LinkedList
### 1. 概览 ### 1. 概览