Copyonwritearraylist source code reading

Source: Internet
Author: User

The Java. util. Concurrent package defines the concurrent collection classes corresponding to common collection classes for efficient processing of concurrent scenarios. The copyonwritearraylist corresponds to the arraylist. As the name implies, copyonwrite is used to copy data during writing. Here, all write operations on the Collection class will create a copy.

Implementation of copyonwritearraylist

Class Definition

public class CopyOnWriteArrayList<E>    implements List<E>, RandomAccess, Cloneable, java.io.Serializable
We can see that no subclass is inherited, and the Implementation interface is similar to arraylist.

Key attributes

/** The lock protecting all mutators */transient final ReentrantLock lock = new ReentrantLock();/** The array, accessed only via getArray/setArray. */private volatile transient Object[] array;
An array is also used for implementation. A volatile declaration is added to ensure thread visibility. No size declaration indicates the actual size of the contained elements. A reentrantlock object declaration is added.

Common Methods

Constructor

Public copyonwritearraylist () {setarray (new object [0]); // an empty array is created by default} public copyonwritearraylist (collection <? Extends E> C) {object [] 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); // copy a set of setarray (elements );}
The size method directly returns the array size, indicating that the array contains only the actual size of space.

public int size() {        return getArray().length;}
The get method is similar to that in arraylist, but it does not have the index range.

public E get(int index) {        return (E)(getArray()[index]);}
Add method, you can see that no matter in the tail or specified position to add, there are locks and unlock operations, before setting the value first copy the original array and expand to size + 1.

Public Boolean add (E) {final reentrantlock lock = This. lock; lock. lock (); // lock try {object [] elements = getarray (); int Len = elements. length; object [] newelements = arrays. copyof (elements, Len + 1); // copy the array attribute and extend it to Length + 1 newelements [Len] = E; setarray (newelements); Return true ;} finally {lock. unlock (); // unlock} 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) // Add newelements = arrays at the end. copyof (elements, Len + 1); else {newelements = new object [Len + 1]; // elements [0, index) ---> newelements [0, index) system. arraycopy (elements, 0, newelements, 0, index); // elements [index, Len) --> newelements [index + 1, Len + 1) system. arraycopy (elements, index, newelements, index + 1, nummoved);} newelements [Index] = element; setarray (newelements);} finally {lock. unlock ();}}
Set method. The Set Method in arraylist directly changes the references in the array. Copy the array and set it again. (The else branch does not understand it. Why does it need to be set to ensure volatile write semantics)

public E set(int index, E element) {final ReentrantLock lock = this.lock;lock.lock();try {    Object[] elements = getArray();    Object oldValue = 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 semanticssetArray(elements);    }    return (E)oldValue;} finally {    lock.unlock();}}
The remove (INT) method is similar to adding a specified position. You need to copy the elements between [0, index) and [index + 1, Len ).

Public E remove (INT index) {final reentrantlock lock = This. lock; lock. lock (); try {object [] elements = getarray (); int Len = elements. length; object oldvalue = elements [Index]; int nummoved = len-index-1; nt if (nummoved = 0) // Delete the last element setarray (arrays. copyof (elements, len-1); else {object [] newelements = new object [Len-1]; // elements [0, index) --> newelements [0, index) system. arraycopy (elements, 0, newelements, 0, index); // elements [index + 1, Len) --> newelements [index, len-1) system. arraycopy (elements, index + 1, newelements, index, nummoved); setarray (newelements);} return (e) oldvalue;} finally {lock. unlock ();}}
Remove (object) method, assign a new array of len-1 size, traverse the original array, if found, copy the elements after the original array to the new array and set the list as a new array, otherwise, the original array is assigned a value to the new array.

public boolean remove(Object o) {final ReentrantLock lock = this.lock;lock.lock();try {    Object[] elements = getArray();    int len = elements.length;    if (len != 0) {// Copy while searching for element to remove// This wins in the normal case of element being presentint newlen = len - 1;Object[] newElements = new Object[newlen];for (int i = 0; i < newlen; ++i) {    if (eq(o, elements[i])) {// found one;  copy remaining and exitfor (int k = i + 1; k < len; ++k)    newElements[k-1] = elements[k];setArray(newElements);return true;    } elsenewElements[i] = elements[i];}// special handling for last cellif (eq(o, elements[newlen])) {    setArray(newElements);    return true;}    }    return false;} finally {    lock.unlock();} }

The implementation of the iterator in arraylist supports fast fail. Once a modification is detected during the traversal process, concurrentmodificationexception is thrown; because the iterator of the copyonwritearraylist will copy multiple copies at the time of modification, there is no concurrent modification problem and concurrentmodificationexception will not be thrown. One-way and two-way iterators are also supported. The iterator and listiterator methods are created through the internal class cowiterator, but the former return interface is limited to one-way iteration iterator <E>.

Cowiterator Definition

/** Snapshot of the array **/private final Object[] snapshot;/** Index of element to be returned by subsequent call to next.  */private int cursor;

Constructor

private COWIterator(Object[] elements, int initialCursor) {            cursor = initialCursor;            snapshot = elements;}
The reference and cursor of the current array will be passed in iterator and listiterator (the method without parameters is 0, and the method with parameters is the corresponding value)

Common Methods

public boolean hasNext() {    return cursor < snapshot.length;}public boolean hasPrevious() {    return cursor > 0;}public E next() {if (! hasNext())        throw new NoSuchElementException();return (E) snapshot[cursor++];}public E previous() {if (! hasPrevious())        throw new NoSuchElementException();return (E) snapshot[--cursor];}
Other methods for adding, removing, and set to modify the container are not implemented. Throw new unsupportedoperationexception ();

Summary

1. the iterator of the copyonwritearraylist retains a reference to the underlying base array for execution. This array is currently at the starting position of the iterator. Because the basic array is not modified (the modification is to copy a new array ), therefore, you only need to ensure the visibility of the array content for its synchronization. Multiple Threads can iterate on the container at the same time without interfering with each other or with the thread that modifies the container. Cocurrentmodificationexception is not thrown, and the returned elements are exactly the same as those when the iterator is created. You do not have to consider the impact of subsequent modification operations.

2. Each modification to the container will copy the underlying array, which requires a certain amount of overhead, especially the large scale of the container. Copyonwritearraylist should be used only when iterative operations are much more than modification operations.




Copyonwritearraylist source code reading

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.