copyonwritearraylist Introduction (JDK 1.8)
Copyonwritearraylist, as the name suggests, always copy, read and write the idea of separation, in layman's terms, when we add elements to a container, not directly to the current container to add, but first copy the current container to a new container, Then add the element to the new container, add the play element, and then the original container's reference points to the new container. Copyonwritearraylist reads are concurrent and does not require a lock, and the JUC package provides two concurrent containers that are implemented using the Copyonwrite idea, copyonwritearraylist and Copyonwritearrayset respectively ( Copyonwritearrayset hold a copyonwritearraylist, many methods are called copyonwritearraylist to implement. Inheritance System
Data Structure
/** the lock protecting all mutators//reentrant
locks for data adjustment
final transient reentrantlock lock = new Reentrantlock ();
/** the array, accessed only via Getarray/setarray. ///
//Storage data array
private transient volatile object[] array;
Construction Method
1. Default Construction
/**
* Sets the array.
* *
final void SetArray (object[] a) {
array = A;
}
/**
* Creates an empty list.
*/Public
copyonwritearraylist () {
setarray (new object[0]);
}
2, initialization through the collection
Public Copyonwritearraylist (COLLECTION< extends e> c) {
object[] elements;
If C is the Copyonwritearraylist type, call its GetArray method directly if
(c.getclass () = = Copyonwritearraylist.class)
elements = ( (copyonwritearraylist<?>) c). GetArray ();
else {
//Call C's ToArray method
elements = C.toarray ();
C.toarray might (incorrectly) not return object[]
if (Elements.getclass ()!= object[].class)
elements = Arra Ys.copyof (Elements, Elements.length, object[].class);
}
SetArray (elements);
}
Get Operation
Because it is an array of access, so you can do random access, fast, while reading operations, do not need to synchronize operations.
Public E get (int index) {return get
(GetArray (), index);
}
Private E get (object[] A, int index) {return
(E) a[index];
}
Add Action
1. Add (e) adds elements to the end of the array, allowing the element to be null
Public boolean Add (E e) {
final reentrantlock lock = This.lock;
Lock
Lock.lock ();
try {
object[] elements = GetArray ();
int len = elements.length;
Copy to new array
object[] newelements = arrays.copyof (elements, Len + 1);
add element
Newelements[len] = e;
Reset Reference Relationship
SetArray (newelements);
return true;
} finally {
//release lock
Lock.unlock ();
}
}
2, add (int index, E Element) adding elements to the specified location
public void Add (int index, E Element) {final Reentrantlock lock = This.lock;
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 element to end newelements = arrays.copyof (elements, Len + 1);
else {newelements = new Object[len + 1];
vacated index position//first copy the elements in front of the original array index to the new array system.arraycopy (elements, 0, newelements, 0, index); The elements behind the original array index are then copied to the new array so that the index position is vacant. System.arraycopy (elements, index, newelements, index + 1
, nummoved);
}//Add elements Newelements[index] = element; Reset reference Relationship SetArray (newelements);
finally {//release lock Lock.unlock (); }
}
Adding operations is actually very simple:
1, add lock
2, copy the original array data to the new array, empty out the need to add the element position (end or other position)
3, set the original array reference point to the new array delete operation
1. Remove (int index) removes data from a location
Public E-Remove (int index) {
final reentrantlock lock = This.lock;
Lock
Lock.lock ();
try {
object[] elements = GetArray ();
int len = elements.length;
Gets the element
E oldValue = Get (elements, index) on which to delete the location;
int nummoved = len-index-1;
if (nummoved = = 0)//delete is the last element
//copy generate a new array and reset the reference relationship
SetArray (arrays.copyof (elements, len-1));
else {
object[] newelements = new object[len-1];
Copy elements to the new array
system.arraycopy (elements, 0, newelements, 0, index);
System.arraycopy (elements, index + 1, newelements, index,
nummoved);
SetArray (newelements);
}
Returns the data to be deleted return
oldValue;
} finally {
lock.unlock ();}
}
2. Remove (Object o) removing an element
public boolean remove (Object o) {//array of stored data object[] Snapshot = GetArray ();
Find element o position int index = INDEXOF (o, snapshot, 0, snapshot.length); If you find it, remove the Operation Copyonwritearraylist return (Index < 0)?
False:remove (o, snapshot, index); }
Private Boolean remove (Object o, object[] snapshot, int index) {final Reentrantlock lock = This.lock;
Lock Lock.lock ();
try {object[] current = GetArray ();
int len = current.length;
If this is not equal, the data is modified by another thread, the new array is generated, and there is no lock control prior to calling remove, and all other threads may have modified the data if (snapshot!= current) FindIndex: {
int prefix = math.min (index, Len); Iterate through the new array to see if there are elements o for (int i = 0; i < prefix; i++) {//current[i]!= Snapshot[i] array changed, its element memory
The address should also be different if (Current[i]!= snapshot[i] && eq (o, current[i)) {index = i; Break FindIndex; Found exit}//If index >=len indicates that the current array is reduced, and that no o element exists in all data, returns False if
(index >= Len) return false;
The deleted element is in the array, referencing the same if (current[index] = O) break findindex; Not yet found, from the Index-len again looking to remove the element o
index = indexOf (o, Current, index, Len);
Not found, returns False if (Index < 0) return false;
//found, copy data to new array, delete data on index object[] newelements = new Object[len-1];
System.arraycopy (current, 0, newelements, 0, index); System.arraycopy (Current, index + 1, newelements, index, len-index-1
);
Sets the new array reference SetArray (newelements);
return true;
finally {Lock.unlock (); }
}Summary
Copyonwritearraylist thread safety, read-write separation, read data without synchronization control, modify the data, will be a separate copy of the array elements to operate, when the operation is completed, set the new array reference.
Copyonwritearraylist allows the stored data to be empty, allows duplicate data, and the elements are ordered (stored in the same order as they were added)
Copyonwritearraylist the underlying data structure is a object[], with an initial capacity of 0, followed by an additional element, a volume of +1, and an array copy again.
Because each adjustment copyonwritearraylist structure, will involve the copy copy of the array, so it is more suitable for the data volume is not very large, read more write less concurrent environment.
Copyonwritearraylist read-write separation, the Copyonwrite container can only ensure the final consistency of data, not guarantee real-time data consistency, when other threads are modifying data, because it is a copy of another copy of data, so the data read at this time may be dirty data.