CopyOnWriteArrayList源碼分析

本節一起學習CopyOnWriteArrayList類的源碼

1.首先看一下類的定義

public class CopyOnWriteArrayList<E>
    implements List<E>, RandomAccess, Cloneable, java.io.Serializable

2.類的變量

    /** 重入鎖用來保護所有的存取器 */
    final transient ReentrantLock lock = new ReentrantLock();

    /** 存儲數據的數組,多線程可見 */
    private transient volatile Object[] array;

3.構造方法

    /**
     * 創建一個空的數組.
     */
    public CopyOnWriteArrayList() {
        setArray(new Object[0]);
    }

    /**
     * 創建一個包含集合c的數組
     */
    public CopyOnWriteArrayList(Collection<? extends E> c) {
        Object[] elements;
        if (c.getClass() == CopyOnWriteArrayList.class)
            elements = ((CopyOnWriteArrayList<?>)c).getArray();
        else {
            elements = c.toArray();
            // c.toArray might (incorrectly) not return Object[] (see 6260652)
            if (elements.getClass() != Object[].class)
                elements = Arrays.copyOf(elements, elements.length, Object[].class);
        }
        setArray(elements);
    }

    /**
     * 創建一個包含數組toCopyIn的數組
     */
    public CopyOnWriteArrayList(E[] toCopyIn) {
        setArray(Arrays.copyOf(toCopyIn, toCopyIn.length, Object[].class));
    }
    /**
     * Sets the array.
     */
    final void setArray(Object[] a) {
        array = a;
    }

4.添加元素

    /**
     * 添加元素e到list的結尾
     */
    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);//拷貝長度+1的新數組
            newElements[len] = e;//設置結尾下標的值
            setArray(newElements);//賦值給array數組
            return true;
        } finally {
            lock.unlock();
        }
    }
    /**
     * 插入element在下標index位置
     */
    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 {//否則,分段複製,留出index位置
                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();
        }
    }

5. 獲取元素

    // Positional Access Operations

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

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

6.移除元素

    /**
     * 移除下標位置index的元素
     */
    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);//獲取下標位置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);//複製舊的數組數據到新的數組,不包含index位置的元素
                System.arraycopy(elements, index + 1, newElements, index,
                                 numMoved);
                setArray(newElements);
            }
            return oldValue;
        } finally {
            lock.unlock();
        }
    }
    /**
     * 移除元素o第一次出現的下標位置的元素
     */
    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)//如果下標位置超過len的長度,返回false
                    return false;
                if (current[index] == o)//仍然在index位置
                    break findIndex;
                index = indexOf(o, current, index, len);//在後半部分查找元素
                if (index < 0)
                    return false;
            }
            Object[] newElements = new Object[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();
        }
    }

7.修改元素

    /**
     * Replaces the element at the specified position in this list with the
     * specified element.
     *
     * @throws IndexOutOfBoundsException {@inheritDoc}
     */
    public E set(int index, E element) {
        final ReentrantLock lock = this.lock;
        lock.lock();
        try {
            Object[] elements = getArray();
            E oldValue = get(elements, index);

            if (oldValue != element) {
                int len = elements.length;
                Object[] newElements = Arrays.copyOf(elements, len);
                newElements[index] = element;
                setArray(newElements);//複製,修改,賦值
            } else {
                // Not quite a no-op; ensures volatile write semantics
                setArray(elements);
            }
            return oldValue;
        } finally {
            lock.unlock();
        }
    }
8.遍歷操作
    public Iterator<E> iterator() {
        return new COWIterator<E>(getArray(), 0);//使用全局變量數組賦值給副本,進行操作
    }
    static final class COWIterator<E> implements ListIterator<E> {
        /** 副本 */
        private final Object[] snapshot;
        /** 指針位置,初始0  */
        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();
        }

        @Override
        public void forEachRemaining(Consumer<? super E> action) {
            Objects.requireNonNull(action);
            Object[] elements = snapshot;
            final int size = elements.length;
            for (int i = cursor; i < size; i++) {
                @SuppressWarnings("unchecked") E e = (E) elements[i];
                action.accept(e);
            }
            cursor = size;
        }
    }


總結:

1.CopyOnWriteArrayList讀操作無鎖,線程安全

2.底層使用一個線程可見的數組維護元素,初始容量爲0,每增加一個元素,則數組長度+1,通過複製將舊的數組移動到新數組。

3.增刪改會使用重入鎖進行加鎖操作,讀取不加鎖

4.遍歷是針對副本的一個遍歷,不會出現併發異常

5.針對讀多寫少的情況,推薦使用CopyOnWriteArrayList




發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章