java數據結構之CopyOnWriteArrayList和CopyOnWriteArraySet

1、什麼是CopyOnWritejava

  CopyOnWrite(寫時複製)簡稱COW,這是一種利用讀寫分離的思想來實現線程安全的程序設計思路。顧名思義該思想就是在寫的時候將原數據複製一份,而後在新的數據中進行一些寫入操做。可是讀相關的操做仍是在原有的數據上進行,等到寫操做完成以後,用新的數據替換老的數據來達到修改數據的目的。CopyOnWrite只須要在寫操做上加鎖,在讀取的時候也能夠進行寫操做,因此效率會更好一點。因爲在寫入操做的時候須要複製一份新的數據,更加佔內存,因此適合在寫入操做比較少讀取操做比較多的狀況下來進行操做。數組

 

2、CopyOnWriteArrayList和CopyOnWriteArraySet安全

  java利用了CopyOnWrite這個思想實現了兩個線程安全的集合CopyOnWriteArrayList和CopyOnWriteArraySet,其中CopyOnWriteArraySet的底層仍是經過CopyOnWriteArrayList來實現的,因此咱們重點來看看CopyOnWriteArrayList。 app

/**
 * CopyOnWriteArrayList 是ArrayList的一個線程安全的變體
 * 經過在進行add或set等操做的時候複製一份原來的數據
 */
public class CopyOnWriteArrayList<E>
    implements List<E>, RandomAccess, Cloneable, java.io.Serializable {
    private static final long serialVersionUID = 8673264195747942595L;
    
    /** The lock protecting all mutators */
    final transient ReentrantLock lock = new ReentrantLock();
    
    /** The array, accessed only via getArray/setArray. */
    private transient volatile Object[] array;
    
    /**
     * Gets the array.  Non-private so as to also be accessible
     * from CopyOnWriteArraySet class.
     */
    final Object[] getArray() {
        return array;
    }
    
    /**
     * Sets the array.
     */
    final void setArray(Object[] a) {
        array = a;
    }
    
    /**
     * Creates an empty list.
     */
    public CopyOnWriteArrayList() {
        setArray(new Object[0]);
    }
    
    /**
     * Creates a list holding a copy of the given array.
     *
     * @param toCopyIn the array (a copy of this array is used as the
     *        internal array)
     * @throws NullPointerException if the specified array is null
     */
    public CopyOnWriteArrayList(E[] toCopyIn) {
        setArray(Arrays.copyOf(toCopyIn, toCopyIn.length, Object[].class));
    }
    
    // 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);
    }
    
    /**
     * 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();
        }
    }
    
    /**
     * 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);
            newElements[len] = e;
            setArray(newElements);
            return true;
        } finally {
            lock.unlock();
        }
    }
    
    /**
     * Removes all of the elements from this list.
     * The list will be empty after this call returns.
     */
    public void clear() {
        final ReentrantLock lock = this.lock;
        lock.lock();
        try {
            setArray(new Object[0]);
        } finally {
            lock.unlock();
        }
    }
}

  經過上面的一些主要方法能夠看到在CopyOnWriteArrayList經過數組來保存數據,其內部建立了一個可重入鎖ReentrantLock的實例lock用來對寫相關的操做進行加鎖,來保證同一時間只有一個副本在進行寫操做。CopyOnWriteArrayList不太適合寫操做比較多的環境,由於頻繁的寫操做會產生不少垃圾,是的垃圾回收壓力會比較大。dom

3、CopyOnWriteArrayList的迭代器ide

  CopyOnWriteArrayList中的迭代器爲COWIterator,從代碼中能夠看出,該迭代器自己是基於當前的數組來建立的,而且迭代器中的方法add、set和remove是不讓使用的,這樣就避免了和寫方法衝突。ui

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();
        }

        @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;
        }
    }

 

4、CopyOnWriteArrayList和ArrayList以及Vectorthis

  Vector:在這三者中出現的最先,而且是線程安全的,它的讀寫方法上都使用了synchronized關鍵字用內置鎖對方法進行了加鎖,因此讀寫操做都須要對鎖進行競爭,效率通常spa

  ArrayList:ArrayList是在vector的基礎上去掉了一些同步操做,因此ArrayList是非線程安全的,效率也是三者中最高的。線程

  CopyOnWriteArrayList:CopyOnWriteArrayList算是前二者的 一個折中的解決方案,經過COW思想在寫操做的時候建立一個數據的副本,而後在副本上進行寫操做。讀操做在原來的數組上進行,兩者互不影響,這樣就可以在寫的同時也能夠進行讀操做,在寫操做完成後,就用新的數組替換原來的數組,達到數據更新的目的,這也是一種讀寫分離的思想。因爲建立了數據的副本,因此的寫入的數據的時候,其餘線程讀的時候可能沒法讀取新的數據,這樣就不能保證數據的強一致性,只能保證最終一致性。

 

5、既然使用了鎖來對寫方法進行了同步爲何還要建立一個數據副原本進行操做

  我我的的 理解是它須要保證數組中的數據在遍歷的時候不能發生改變,因此須要建立一個數據副本。

相關文章
相關標籤/搜索