Java. util. Concurrent. copyonwritearraylist copyonwritearrayset

Source: Internet
Author: User
Tags concurrentmodificationexception

Copyonwritearraylist

I. Introduction

The new concurrent package is added to JDK 5, which contains many concurrent containers. These containers are optimized for the multi-threaded environment and greatly improve the execution efficiency of the container class in the concurrent environment.

The copyonwritearraylist class is the implementation of a thread-safe list interface. When writing elements within the class, the underlying array will be completely copied, this is very suitable for applications with far more read operations than write operations. When performing operations on the copyonwritearraylist, the read operation does not need to be locked, but the write operation class locks it.

II. Specific implementation

The underlying definition of copyonwritearraylist is as follows:

 

Public class copyonwritearraylist <E> implements list <E>, randomaccess, cloneable, Java. io. serializable {private volatile transient E [] array; private e [] array () {return array;} // this operation is locked, prevent array from being replaced with private synchronized void copyin (E [] tocopyin, int first, int N) {array = (E []) New object [N]; system. arraycopy (tocopyin, first, array, 0, n );}...}

Read/write operations:

Public class copyonwritearraylist <E> implements list <E>, randomaccess, cloneable, Java. io. serializable {public e get (INT index) {// because the operations include rangecheck and index, instead of directly executing // on the array, the local variable elementdata is used to reference the array, prevent replacement between two operations // array E [] elementdata = array (); rangecheck (index, elementdata. length); Return elementdata [Index];} public synchronized e set (INT index, e element) {// synchronous int Len = array. lengt H; rangecheck (index, Len); e oldvalue = array [Index]; // determine whether the written element is the same as the original data. boolean same = (oldvalue = element | (element! = NULL & element. Equals (oldvalue); If (! Same) {// [1] Create a new array and copy the original array value to the new array E [] newarray = (E []) New object [Len]; system. arraycopy (array, 0, newarray, 0, Len); // [2] Set element newarray [Index] = element; // [3] Replace the underlying array = newarray;} return oldvalue ;}...}

Add and remove use the same technology:

Public class copyonwritearraylist <E> implements list <E>, randomaccess, cloneable, Java. io. serializable {public synchronized Boolean add (E element) {// [1] New and copy int Len = array. length; E [] newarray = (E []) New object [Len + 1]; system. arraycopy (array, 0, newarray, 0, Len); // [2] add element newarray [Len] = element; // [3] Change base array = newarray; return true;} public synchronized e remove (INT index) {int Len = array. length; rangecheck (index, Len); e oldvalue = array [Index]; // new a new array E [] newarray = (E []) New object [len-1]; // The system element before the copy index. arraycopy (array, 0, newarray, 0, index); // copy the remaining element int nummoved = len-index-1; if (nummoved> 0) system. arraycopy (array, index + 1, newarray, index, nummoved); // replace array reference array = newarray; return oldvalue ;}...}

Note: The iterator obtained on the copyonwritearraylist cannot perform the set and remove operations. Otherwise, an exception is thrown.

 

In addition to locking, there is actually another way to prevent concurrent modification exceptions. This is the read/write splitting technology (not on the database ).

Let's look back at the next common sense:

1. in Java, the "=" operation only associates a reference with an object. If a thread points a reference to another object, a thread obtains the object pointed to by the reference, so there will be no concurrentmodificationexception between them. They are blocked at the virtual machine level, and the speed is very fast and almost no CPU time is required.

2. Two different references in Java point to the same object. When the first reference points to another object, the second reference will keep the original object.

 

Based on the above knowledge, let's discuss the following question:

To process write operations (including add, remove, and set) in copyonwritearraylist, the original data is first generated into a new array through arrays. copyof () of jdk1.6.

Write data on the new data object, and point the original reference to the current data object after writing the Data Object (common sense 1 is applied here ), this ensures that each write operation is performed on a new object (because of the consistency of write operations, a lock is required for various write operations, and jdk1.6 uses a re-entry lock here ),

Then, the system reads the referenced current object (including get and iterator) without locking or blocking. For iterator, a castrated version iterator called cowiterator is used, because write operations are not supported, when you get the iterator of copyonwritearraylist, the data reference in the iterator is directed to the Data Object pointed to by the current reference, no matter what future write operations, the data object reference in the iterator will not be changed any more, so the iterator is safe (Common Sense 2 is applied here ).

The write operation in copyonwritearraylist needs to copy an array in a large area, so the performance is definitely poor. However, because the operation object and the write operation are not the same object, no locks are required between the read operations, the synchronization process between read and write operations only points the reference to a new array object through a simple "=" after writing, which almost does not require time, in this way, the read operation is very fast and safe. It is suitable for multi-threaded use, and concurrentmodificationexception will never occur. Therefore, it is concluded that copyonwritearraylist is suitable for scenarios where the read operation is much larger than the write operation, such as caching.

 

The basic principle of copyonwritearrayset is the same as that of copyonwritearrayset, which includes:

Private Final copyonwritearraylist <E> Al;

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.