CopyOnWriteArrayList是一個執行緒安全的List實現,其在對物件進行讀操作時,由於物件沒有發生改變,因此不需要加鎖,反之在物件進行增刪等修改操作時,它會先複製一個物件副本,然後對副本進行修改,最後將修改後的副本物件寫回,從而保證操作的執行緒安全,下面我們看一下具體的程式碼實現。
###建構函式
通過CopyOnWriteArrayList連結串列的構造,可以看出主要是依賴ReentrantLock與陣列實現執行緒安全的連結串列
/** The lock protecting all mutators */
final transient ReentrantLock lock = new ReentrantLock();
/** The array, accessed only via getArray/setArray. */
private transient volatile Object[] array;
/**
* Creates an empty list.
*/
public CopyOnWriteArrayList() {
setArray(new Object[0]);
}
add是一個標準的使用ReentrantLock加鎖保證執行緒安全操作的實現
/**
* Appends the specified element to the end of this list.
*
* @param e element to be appended to this list
* @return {@code true} (as specified by {@link Collection#add})
*/
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);//copy一個副本物件
newElements[len] = e;//賦值
setArray(newElements);//把物件寫回去
return true;
} finally {
lock.unlock();//釋放鎖
}
}
/**
* Inserts the specified element at the specified position in this
* list. Shifts the element currently at that position (if any) and
* any subsequent elements to the right (adds one to their indices).
*
* @throws IndexOutOfBoundsException {@inheritDoc}
*/
public void add(int index, E element) {
final ReentrantLock lock = this.lock;
lock.lock();
try {
Object[] elements = getArray();//獲取自身陣列物件
int len = elements.length;
if (index > len || index < 0)//判斷是否越界
throw new IndexOutOfBoundsException("Index: "+index+
", Size: "+len);
Object[] newElements;
int numMoved = len - index;//計算需要移動的陣列長度
if (numMoved == 0)
newElements = Arrays.copyOf(elements, len + 1);
else {
newElements = new Object[len + 1];
System.arraycopy(elements, 0, newElements, 0, index);
System.arraycopy(elements, index, newElements, index + 1,
numMoved);
}
newElements[index] = element;//賦值
setArray(newElements);//把物件寫回去
} finally {
lock.unlock();//釋放鎖
}
}
在remove的實現中我們可以看到在實際執行操作之前,會對物件的執行緒安全進行再次檢查,另外在執行定位下標操作時基於原有下標進行分段定位的優化,一定概率上會降低迴圈複雜度
public E remove(int index) {
final ReentrantLock lock = this.lock;
lock.lock();//加鎖
try {
Object[] elements = getArray();//獲取自身陣列物件
int len = elements.length;
E oldValue = get(elements, index);//根據下標取值
int numMoved = len - index - 1;//計算需要移動的陣列長度
if (numMoved == 0)
setArray(Arrays.copyOf(elements, len - 1));
else {
Object[] newElements = new Object[len - 1];//宣告一個新陣列
System.arraycopy(elements, 0, newElements, 0, index);
System.arraycopy(elements, index + 1, newElements, index,
numMoved);
setArray(newElements);
}
return oldValue;
} finally {
lock.unlock();
}
}
public boolean remove(Object o) {
Object[] snapshot = getArray();
int index = indexOf(o, snapshot, 0, snapshot.length);//遍歷陣列定位元素下標
return (index < 0) ? false : remove(o, snapshot, index);
}
/**
* A version of remove(Object) using the strong hint that given
* recent snapshot contains o at the given index.
*/
private boolean remove(Object o, Object[] snapshot, int index) {
final ReentrantLock lock = this.lock;
lock.lock();//加鎖
try {
Object[] current = getArray();
int len = current.length;
//以下這段程式碼保證傳輸執行緒安全,再次對陣列是否發生改變進行判斷,如果發生改變進行分段輪詢,提高效率
if (snapshot != current) findIndex: {//這裡判斷陣列是否已經被修改,如果有修改就重新定位下標
int prefix = Math.min(index, len);//取最小值
for (int i = 0; i < prefix; i++) {//提高效率先按最小回圈次數遍歷
if (current[i] != snapshot[i] && eq(o, current[i])) {
index = i;
break findIndex;
}
}
if (index >= len)//下標超過當前陣列長度返回false
return false;
if (current[index] == o)//下標未改變,直接返回
break findIndex;
index = indexOf(o, current, index, len);//遍歷剩餘部分
if (index < 0)
return false;
}
Object[] newElements = new Object[len - 1];//建立一個長度len - 1的陣列,執行復制操作
System.arraycopy(current, 0, newElements, 0, index);
System.arraycopy(current, index + 1,
newElements, index,
len - index - 1);
setArray(newElements);//覆蓋原陣列
return true;
} finally {
lock.unlock();
}
}
讀操作非常簡單,無需加鎖
/**
* {@inheritDoc}
*
* @throws IndexOutOfBoundsException {@inheritDoc}
*/
public E get(int index) {
return get(getArray(), index);
}
@SuppressWarnings("unchecked")
private E get(Object[] a, int index) {
return (E) a[index];
}
通過對原始碼的分析,可以看到CopyOnWriteArrayList只在需要保證執行緒安全的寫操作上加鎖,核心思想就是減少鎖競爭,從而提高並行時的讀取效能,適用於寫少讀多的應用場景。
以上就是對CopyOnWriteArrayList內部核心原始碼的基本走讀與解析,其執行緒安全的實現模式很有代表意義,十分值得初學者參考與學習,希望對大家能有所幫助,其中如有不足與不正確的地方還望指正與海涵,十分感謝。
關注微信公眾號,檢視更多技術文章。