CopyOnWriteArrayList 源碼分析 (基于Java 8)

1. CopyOnWriteArrayList 功能簡介

CopyOnWriteArrayList 是juc中提供的 并發安全的 ArrayList, 我們拆分一下類名 "Copy" "On" "Write" "ArrayList", 從字面意思我們推斷出, 這個是以在 Write 時進行 Copy 數組元素的 ArrayList.
它主要具有一下特性:

  1. 所有元素都存儲在數組里面, 只有當數組進行 remove, update時才在方法上加上 ReentrantLock , 拷貝一份 snapshot 的數組, 只改變 snapshot 中的元素, 最后再賦值到 CopyOnWriteArrayList 中
  2. 所有的 get方法只是獲取數組對應下標上的元素(無需加鎖控制)

從上面兩個特性我們也知道: CopyOnWriteArrayList 是使用空間換時間的方式進行工作, 它主要適用于 讀多些少, 并且數據內容變化比較少的場景(最好初始化時就進行加載數據到CopyOnWriteArrayList 中)

2. 元素添加 add 方法

直接添加元素 e 到數組的尾部

/**
 * Appends the specified element to the end of this list
 *
 * @param e element to be appeded to this list
 * @return {@code true} (as specified by {@link Collection#add})
 */
@Override
public boolean add(E e) {
    /**
     * 增加元素 e 到數組的末尾
     * 操作步驟:
     *  1. 獲取全局的 reentrantLock
     *  2. 將原來的 array1 copy 到一個 array.length + 1 的數組 array2 里面
     *  3. 將 先添加的元素e添加到新數組 array2 的最后一個空間里面 (array2[array2.length - 1] = e)
     *  4. 將 新數組 array2 賦值給 CopyOnWriteArrayList 中的 array
     */
    final ReentrantLock lock = this.lock;
    lock.lock();                                                    // 1. 獲取 全局 lock
    try{
        Object[] elements = getArray();                             // 2. 獲取原來的數組
        int len = elements.length;
        Object[] newElements = Arrays.copyOf(elements, len + 1);    // 3. 新建一個 array2 將原來的數據賦值到這個新建的數組里面
        newElements[len] = e;                                       // 4. 將 e 賦值給 array2的最后一個空間里面
        setArray(newElements);                                      // 5. 將新數組 array2 賦值給 CopyOnWriteArrayList 中的 array
        return true;
    }finally {
        lock.unlock();                                              // 6. 釋放鎖
    }

}

添加元素到數組的指定位置

    /**
     * Inserts the specified element at the specified position in this
     * list. Shifts the lement currently at that position (if any) and
     * any subsequent elements to the right (adds one to their indices)
     */
    @Override
    public void add(int index, E element) {
        /**
         * 將元素 e 插入到數組 指定的索引下標 index 下
         * 操作步驟:
         *      1. 獲取全局的鎖
         *      2. 獲取 CopyOnWriteArrayList 的 array, 及 array.length
         *      3. 進行參數校驗 (index > len || index < 0) 則直接拋異常 -> 說明元素的插入只能在 0 - array.length 之間(包含兩個端點)
         *      4. 獲取插入點 index 與 array.length 之間的步長, 進行分類討論
         *          1) 插入的數據正好在 原array數組的后一個節點 (numMoved = len), 則直接新建一個 array, 將原來的 array copy 過來
         *          2) 插入的 index 滿足 0 <= index <= len - 1, 則新建一個數組, 原來 o -> index(index不包含) 拷貝來, index后面的數據拷貝到新數組的 index + 1 的空間
         *      5. 將 e 設置到 新 array 的 index 位置
         *      6. 將 新 array 設置到 CopyOnWriteArrayList 里面
         */
        final ReentrantLock lock = this.lock;
        lock.lock();                                                                    // 1. 獲取全局的鎖
        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){ // 走到這一步, 說明 數據是插入到 oldArray.length(這個值是指下標) 位置上的元素
                newElements = Arrays.copyOf(elements, len + 1); // 直接拷貝原數組到一個新的 array 數組中, 這個數組的長度是 len + 1
            }else{
                newElements = new Object[len + 1];
                System.arraycopy(elements, 0, newElements, 0, index); // 將原數組 index 前的數組都拷貝到新的數組里面
                System.arraycopy(elements, index, newElements, index + 1, numMoved); // 將原數組 index 以后的元素都 copy到新的數組里面(包括index位置的元素)
            }
            newElements[index] = element; // 將 index 賦值 element
            setArray(newElements); // 將 新的 array set到 CopyOnWriteArrayList 上
        }finally {
            lock.unlock();
        }

    }

將元素 e 插入到數組 指定的索引下標 index 下 (整個操作比較簡單)
操作步驟:

  1. 獲取全局的鎖
  2. 獲取 CopyOnWriteArrayList 的 array, 及 array.length
  3. 進行參數校驗 (index > len || index < 0) 則直接拋異常 -> 說明元素的插入只能在 0 - array.length 之間(包含兩個端點)
  4. 獲取插入點 index 與 array.length 之間的步長, 進行分類討論
    1. 插入的數據正好在 原array數組的后一個節點 (numMoved = len), 則直接新建一個 array, 將原來的 array copy 過來
    2. 插入的 index 滿足 0 <= index <= len - 1, 則新建一個數組, 原來 o -> index(index不包含) 拷貝來, index后面的數據拷貝到新數組的 index + 1 的空間
  5. 將 e 設置到 新 array 的 index 位置
  6. 將 新 array 設置到 CopyOnWriteArrayList 里面
2. 元素刪除 remove 方法

刪除指定索引 index 上的元素

/**
 * Removes the element at the specified position in this list.
 * Shifts any subsequent elements to the left (subtracts one from their
 * indices). Returns the lement that was removed from the list
 */
@Override
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){ // 說明刪除的元素的位置在 len - 1 上, 直接拷貝原數組的前 len - 1 個元素
            setArray(Arrays.copyOf(elements, len - 1));
        }else{
            Object[] newElements = new Object[len - 1];
            System.arraycopy(elements, 0, newElements, 0, index); // 拷貝原數組 0 - index之間的元素 (index 不拷貝)
            System.arraycopy(elements, index + 1, newElements, index, numMoved); // 拷貝原數組 index+1 到末尾之間的元素 (index+1也進行拷貝)
            setArray(newElements);
        }
    }finally {
        lock.unlock();
    }
    return null;
}

直接刪除元素 e

public boolean remove(Object o){
    Object[] snapshot = getArray();
    // 獲取 index 在 snapshot 中的位置, -1 表示不存在
    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;
        // findIndex: <- 這個用法平時用的比較少, 在這里, 只要 break findIndex, 那 if(snapshot != current) 這里括號里面的其他代碼就不執行了, 直接跳到括號外面, 建議寫個小demo試一下
        if(snapshot != current) findIndex:{ // snapshot != current 表示數組被另外一個線程操作過, 有變化
            /**
             * 下面的操作是發生在 調用方法 "remove(Object o)" 中的 "indexOf"后 , 數組 array 發生變化而做的查詢修正工作
             * 主要分 下面 4 中情況:
             *  1. 從 index,len 中取出一個較小的值 prefix, 從 current的prefix前個元素中尋找元素 o, 找到后, 直接 break, 執行下面的操作
             *  2. 若 index >= len, 則說明 元素 o 在另外的線程中已經被刪除, 直接 return
             *  3. current[index] = o, 則說明, index 位置上的元素 o 還在那邊, 直接 break
             *  4. 最后 在 index 與 len 之間尋找元素, 找到位置直接接下來的代碼, 沒找到 直接 return
             */
            int prefix = Math.min(index, len);
            for(int i = 0; i < prefix; i++){
                // 找出 current 數組里面 元素 o 所在的位置 i, 并且賦值給 index
                if(current[i] != snapshot[i] && eq(o, current[i])){
                    index = i;
                    break findIndex;
                }
            }

            if(index >= len){ // index >= len 表示元素 o 已經被刪除掉
                return false;
            }
            if(current[index] == o){ // 元素 o 也在數組 current 的 index 位置
                break findIndex;
            }
            index = indexOf(o, current, index, len); // 在 current 中尋找元素 o 所在的位置 (這里不會出現 index > len 的情況, 上面的代碼中已經做了判斷)
            if(index < 0){ // 要刪除的元素 在另外的線程中被刪除掉了, 直接 return false
                return false;
            }
        }

        Object[] newElements = new Object[len - 1]; // 新建一個 len - 1 長度的數組
        System.arraycopy(current, 0, newElements, 0, index); // 拷貝老數組前 index 個元素
        System.arraycopy(current, index + 1, newElements, index, len - index - 1); // 拷貝 老數組 index + 1 后的元素 ( index + 1 包含)
        setArray(newElements);
        return true;
    }finally {
        lock.unlock();
    }
}

代碼稍微多一點, 主要樹為了再第一步獲取 數組 與第二步操作之間因并發導致 snapshot 與原數組元素不一致, 而做了修復的操作;
數據不一致主要通過 snapshot != current 進行判斷
修復操作主要分 下面 4 中情況:

  1. 從 index,len 中取出一個較小的值 prefix, 從 current的prefix前個元素中尋找元素 o, 找到后, 直接 break, 執行下面的操作
  2. 若 index >= len, 則說明 元素 o 在另外的線程中已經被刪除, 直接 return
  3. current[index] = o, 則說明, index 位置上的元素 o 還在那邊, 直接 break
  4. 最后 在 index 與 len 之間尋找元素, 找到位置直接接下來的代碼, 沒找到 直接 return
3. 元素替換 set 方法
   /**
 * Replaces the element at the specified position in this list with the
 * specified element
 */
@Override
public E set(int index, E element) {
    /**
     * 將數組 array 指定位置 index 用元素 element 進行替代
     * 操作步驟:
     *      0. 獲取全局的 ReentrantLock
     *      1. 獲取數組指定下標 index 上的元素
     *      2. 判斷 element 是否與來源數組中的元素一致
     *          1) 不一致, 則獲取原數組的 一個 snapshot, 并且將對應位置 index 進行替換
     *          2) 一致, setArray(elements) <- 這個其實是說明都沒做
     *      3. 在 finally 中釋放 鎖
     *
     */
    final ReentrantLock lock = this.lock;
    lock.lock();                                                    // 0. 獲取鎖
    try {
        Object[] elements = getArray();
        E oldValue = get(elements, index);                          // 1. 獲取原數組中對應index位置的元素

        if(oldValue != element){
            int len = elements.length;
            Object[] newElements = Arrays.copyOf(elements, len);    // 2. 獲取原數組的一個 snapshot 版本
            newElements[index] = element;                           // 3. 在 index 位置進行 set 新的值
            setArray(newElements);                                  // 4. 將 snapshot 版本的數組覆蓋原來的數組
        }else{
            // Not quite a no-op; ensures volatile write semantics
            setArray(elements);
        }
    }finally {
        lock.unlock();                                              // 5. 釋放鎖
    }
    return null;
}

set方法比較簡單, 一般直接看代碼就 OK 了;

3. 總結
  1. CopyOnWriteArrayList 是使用空間換時間的方式進行工作
  2. 它主要適用于 讀多些少, 并且數據內容變化比較少的場景(最好初始化時就進行加載數據到CopyOnWriteArrayList 中)
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容