JDK容器學習之CopyOnWriteArrayList:線程安全保障機制

JDK容器學習之CopyOnWriteArrayList

列表容器常見的有 ArrayListLinkedList,然而二者都是非線程安全的,若應用場景對線程安全有需求,則可使用CopyOnWriteArrayList來代替傳統的Vectorjava

I. 存儲結構

先看下類中定義的成員變量, 一個數組和一個鎖數組

/** The lock protecting all mutators */
final transient ReentrantLock lock = new ReentrantLock();

/** The array, accessed only via getArray/setArray. */
private transient volatile Object[] array;

array: 保存了列表中的數據安全

lock: 修改時加鎖,用於保證線程安全數據結構

底層數據結構依然是數組,相交於ArrayList而言,少了一個表示數組長度的size變量,獲取列表長度是經過下面的方法多線程

public int size() {
    return getArray().length;
}

final Object[] getArray() {
    return array;
}

留一個問題:併發

爲何獲取鏈表的長度個ArrayList的使用姿式不一樣,這樣作有什麼好處源碼分析

II. 讀取,刪除,添加實現邏輯

1. 讀取數據

讀數據,帶兩個疑問進行看源碼性能

  • 讀取是否加鎖
  • 若加鎖性能如何保證;若不加鎖線程安全如何保證

先看實現源碼學習

private E get(Object[] a, int index) {
    return (E) a[index];
}

/**
 * {@inheritDoc}
 *
 * @throws IndexOutOfBoundsException {@inheritDoc}
 */
public E get(int index) {
    return get(getArray(), index);
}

結果比較清晰測試

  • 讀數據不加鎖
  • 線程安全保障先給個簡單的說明,後面內容詳細補充
    • 數組定義爲volatile,確保最新改動對多線程可見
    • private transient volatile Object[] array;

2. 刪除元素

直接在源碼中加上一些註釋

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) { // 刪除最後一個元素時
          //直接進行數組拷貝,而後將tables數組引用指向拷貝後的數組
          setArray(Arrays.copyOf(elements, len - 1));
      } else {
          // 建立一個新的數組,將舊數組內容拷貝到新數組中
          // 而後將tables數組引用指向新的數組
          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();
  }
}

從刪除的實現,可肯定如下幾點:

  • 修改加鎖,確保同一時刻只有一個線程對數組進行修改
  • 修改並非在原數組上進行的,而是建立一個新的數組,在新的數組上進行操做操做,而後將tables引用指向新的數組
  • 修改必然會涉及到數組內容的拷貝

3. 新增元素

ArrayList新增元素時,可能致使數組擴容;CopyOnWriteArrayList在列表的修改時,採用數組拷貝,在新的數組上進行操做,從這點出發,應該不存在擴容的問題,由於每次修改都會致使數組的從新拷貝

從代碼出發,驗證上面的觀點

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;
        // 將tables引用指向新的數組
        setArray(newElements);
    } finally {
        lock.unlock();
    }
}

從實現得出如下幾個結論

  • CopyOnWriteArrayList沒有數組擴容一說,由於每次修改都會建立一個新的數組
  • 修改加鎖,確保只有一個線程對列表進行修改

新增元素示意圖

輸入圖片說明

III. 線程安全測試

在List的遍歷過程當中,新增,刪除or修改其中元素值時,會出現什麼問題?

先寫個測試demo

public class CopyOnWriteTest {
    List<String> list = new CopyOnWriteArrayList<>(
            new String[]{
                    "1", "2", "3", "4", "5", "6", "7", "8", "9"
            }
    );

    private void modify() {
        new Thread(() -> {
            list.add(8, "a8");
            list.remove(9);
            list.set(6, "6666");
            System.out.println("----修改完成----");
        }).start();
    }

    @Test
    public void testModify() throws InterruptedException {
        Iterator<String> iterable = list.iterator();
        int i = 0;
        while (iterable.hasNext()) {
            if (i++ == 1) {
                modify();
            } else if (i == 4) {
                Thread.sleep(1000);
            }
            System.out.println("index: " + i + " value: " + iterable.next());
        }
        
        Thread.sleep(1000);
        System.out.println(list);
    }
}

輸出結果

index: 1 value: 1
index: 2 value: 2
index: 3 value: 3
----修改完成----
index: 4 value: 4
index: 5 value: 5
index: 6 value: 6
index: 7 value: 7
index: 8 value: 8
index: 9 value: 9
[1, 2, 3, 4, 5, 6, 6666, 8, a8]

發如今迭代的過程當中,對列表進行修改,是不會影響迭代過程的,遍歷的依然是原來的數組;(順帶說一句,若是換成ArrayList會拋併發修改的異常)

探究下原理,主要是由於 CopyOnWriteArrayList的迭代器的實現方式

static final class COWIterator<E> implements ListIterator<E> {
    /** Snapshot of the array */
    private final Object[] snapshot;
    /** Index of element to be returned by subsequent call to next.  */
    private int cursor;

    private COWIterator(Object[] elements, int initialCursor) {
        cursor = initialCursor;
        snapshot = elements;
    }

    public boolean hasNext() {
        return cursor < snapshot.length;
    }

    public boolean hasPrevious() {
        return cursor > 0;
    }

    @SuppressWarnings("unchecked")
    public E next() {
        if (! hasNext())
            throw new NoSuchElementException();
        return (E) snapshot[cursor++];
    }

    @SuppressWarnings("unchecked")
    public E previous() {
        if (! hasPrevious())
            throw new NoSuchElementException();
        return (E) snapshot[--cursor];
    }

    public int nextIndex() {
        return cursor;
    }

    public int previousIndex() {
        return cursor-1;
    }

    /**
     * Not supported. Always throws UnsupportedOperationException.
     * @throws UnsupportedOperationException always; {@code remove}
     *         is not supported by this iterator.
     */
    public void remove() {
        throw new UnsupportedOperationException();
    }

    /**
     * Not supported. Always throws UnsupportedOperationException.
     * @throws UnsupportedOperationException always; {@code set}
     *         is not supported by this iterator.
     */
    public void set(E e) {
        throw new UnsupportedOperationException();
    }

    /**
     * Not supported. Always throws UnsupportedOperationException.
     * @throws UnsupportedOperationException always; {@code add}
     *         is not supported by this iterator.
     */
    public void add(E e) {
        throw new UnsupportedOperationException();
    }
}

從源碼分析可得知

  1. 構造方法,確保迭代器持有一份對數組的引用,後續的迭代是針對這個數組進行的;若在迭代過程當中,列表發生修改,使得List的數組引用指向新的數組,也不會改變迭代器中對原數組的引用,因此依然遍歷的是舊數組
  2. 由於上面的原則,迭代過程當中,不容許對數組進行修改

IV. 對比&小結

List容器中,VectorCopyOnWriteArrayList都是線程安全的,下面則主要對比下二者的實現邏輯

1. Vector

  • 全部接口都加鎖
  • 多線程訪問時,致使鎖的競爭,致使效率低下

2. CopyOnWriteArrayList

  1. 底層結構:數組
  2. 讀取接口,無鎖
  3. 修改列表,加鎖,確保始終只有一個線程在修改列表內容
  4. 修改方式:
    • 將原數組內容拷貝到新的數組,直接修改新數組
    • 而後將新數組賦值給列表的數組引用(array)
  5. 每次修改都會先上鎖,而後進行數組拷貝,因此性能較 ArrayList低;讀取無鎖,因此讀的性能比Vector高(沒有競爭)
  6. 遍歷時,是對列表中當前所指向的數組進行遍歷,遍歷過程當中對數組的修改,不會影響遍歷的內容
  7. 默認初始容量爲0

掃描關注,java分享

相關文章
相關標籤/搜索