Copyonwritearraylist is a collection class used in the jdk1.5 parallel package to process high concurrency and reduce lock wait when multiple reads and writes are less. Perform a brief analysis on the implementation of this class.
1. First, copyonwritearraylist implements the list interface and implements methods related to the = List interface.
2. The add method of the following will first lock, then copy the array in the original list, and then add 1 to the length of the new array to release the lock. Because the array copy speed is very fast, the lock overhead is relatively small when the number of reads and writes is small.
Public Boolean add (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 ();}}
2. Its cowiterator does not fail quickly. The following is its source code.
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 ++];}
3. The remove method is shown below. The locking principle is the same as the add method.
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) setarray (arrays. copyof (elements, len-1); else {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 ();}}
JDK package copyonwritearraylist source code analysis