CopyOnWriteArrayList實現讀寫分離,話不多說,上源碼:
add採用synchronized進行加鎖的,get直接根據下標獲取數據。
/**
* The lock protecting all mutators. (We have a mild preference
* for builtin monitors over ReentrantLock when either will do.)
*/
final transient Object lock = new Object();
public boolean add(E e) {
synchronized (lock) {
Object[] es = getArray();
int len = es.length;
es = Arrays.copyOf(es, len + 1);
es[len] = e;
setArray(es);
return true;
}
}
/**
* {@inheritDoc}
*
* @throws IndexOutOfBoundsException {@inheritDoc}
*/
public E get(int index) {
return elementAt(getArray(), index);
}
// Positional Access Operations
@SuppressWarnings("unchecked")
static <E> E elementAt(Object[] a, int index) {
return (E) a[index];
}
add的時候先copy數據,然後在該數據的基礎上將新元素插入到尾部,最後再將原容器的引用指向新的容器。
應用場景:讀多寫少的併發場景
缺點:
- 內存開銷較大,寫操作的時候,內存會同時駐紮兩個對象的內存,內存佔用較大,當存儲數據過大時會造成內存溢出,同時也會引起full gc和yong gc, 系統響應會變慢。可通過壓縮技術或者使用concurrentHashMap來實現。
- 只能保證結果最終一致性,不能保證結果實時一致性
性能分析,參考如下鏈接:http://blog.csdn.net/wind5shy/article/details/5396887