Copyonwritearraylist is a thread-safe, read-only ArrayList that is not locked.
Unlike the ArrayList default initialization size of 10 object[],copyonwritearraylist The default initialization size is 0 object[]
1,add (E)
The Add method does not add the Synchronized keyword to the entire method, but uses Reentrantlock to ensure thread safety.
This method is different from the Add method of ArrayList, ArrayList, if the number of elements in the list exceeds object[] size at Add, the expansion is The default expansion is 1.5 times times, while Copyonwritearraylist is creating a new array of 1 larger than the original, and then putting the new element at the end.
2,remove (E)
In the ArrayList remove method, the code is as follows:
Public E Remove (int= (e) elementdata[index]; int nummoved = size-index-1; if (nummoved > 0) System.arraycopy (elementdata, index+1, Elementdata, index, nummoved); elementdata[null / let GCdoes its workreturn oldValue;}
As can be seen from the code, ArrayList is directly manipulating the original array, using System.arraycopy to move the elements after index forward.
In the copyonwritearraylist remove, as with the Add method, it is also reentrantlock to ensure thread safety, the code is as follows:
PublicE Remove (intindex) {FinalReentrantlock lock = This. Lock;lock.lock ();Try{object[] elements=GetArray (); intLen =elements.length; Object OldValue=Elements[index]; intnummoved = len-index-1; if(nummoved = = 0) SetArray (arrays.copyof (elements, Len-1)); Else{object[] newelements=NewObject[len-1]; System.arraycopy (Elements,0, newelements, 0, index); System.arraycopy (elements, index+ 1, Newelements, index,nummoved); SetArray (newelements); } return(E) OldValue;} finally{Lock.unlock ();} }
As can be seen from the code, Copyonwritearraylist creates a new array of size 1 smaller than the original, and then uses System.arraycopy to copy the original array to the new array two times before and after the index.
Java Concurrency copyonwritearraylist