Java Concurrency Programming and Technology Insider: Copyonwritearraylist, Copyonwritearrayset source analysis

Source: Internet
Author: User

Lin Bingwen Evankaka Original works. Reprint please specify the source Http://blog.csdn.net/evankaka
Absrtact: This paper mainly discusses the source code analysis of Copyonwritearraylist and Copyonwritearrayset in Java.

One, copyonwritearraylist source analysis

Copyonwritearraylist is not very much used in Java concurrency scenarios, because it does not fully guarantee the correctness of the read data. Its main features are as follows:
1, suitable for the scene read more write less
2, it is not guaranteed to read the data must be correct, because the get is not locked
3, add, remove will be added to lock and then to operate

below to see the source code:
The data structures contained

public class copyonwritearraylist<e> implements List<e>, Randomaccess, cloneable, java.io.Serializable {/* * Re-entry lock */transient final reentrantlock lock = new Reentrantlock ()/** real data structure */private volatile transient object[] array;

In fact, its data structure is very simple, is an array and a re-entry lock.

There are three constructor functions:

/*** constructor, create an empty array */public copyonwritearraylist () {SetArray (new object[0]);} /*** constructor, from the collection to initialize the list */public copyonwritearraylist (collection<? extends e> c) {object[] elements = C.toarray (); if ( Elements.getclass ()! = Object[].class) elements = arrays.copyof (elements, Elements.length, object[].class);// Converts elements array contents to object type SetArray (elements);} The/*** constructor, from the array to initialize the list */public copyonwritearraylist (e[] tocopyin) {SetArray (arrays.copyof, Tocopyin, Object[].class));///Note that all upward transitions to object type}

Main methods:

1. Add lock when added

Public boolean Add (E e) {final Reentrantlock lock = This.lock;lock.lock ();//Get lock try {   object[] elements = GetArray (); 
   int len = elements.length;   object[] newelements = arrays.copyof (elements, Len + 1);//Copy the current elements to an array of length plus 1   newelements[len] = e;// Sets the last element to be e   setarray (newelements);//sets the current element array, where it is possible to make an error return true if a get is executed   ;} finally {   lock.unlock () ;//Release Lock}
Here's a note on this method:

Addifabsent This method Copyonwritearrayset will be used (in fact Copyonwritearrayset is encapsulated a copyonwritearraylist, the following will be said)

If it already exists, do not put public boolean addifabsent (e) {final Reentrantlock lock = This.lock;lock.lock ();//Get lock try {    object[] Ele ments = GetArray ();    int len = elements.length;    object[] newelements = new Object[len + 1];    for (int i = 0; i < len; ++i) {//An element is taken out to compare if (eq (e, elements[i])    return false;//jumps out, the element already exists in list (else    Newe Lements[i] = elements[i]; A copy to a new array    }    Newelements[len] = e;    SetArray (newelements);//Set new array    return true;//join succeeded} finally {    lock.unlock ();//Release lock}    }



2. Lock in when deleted
Delete Method One

Public E Remove (int index) {final Reentrantlock lock = This.lock;lock.lock ();//Get lock try {   object[] elements = GetArray () ;   int len = elements.length;   Object OldValue = elements[index];//The element to be deleted   int nummoved = len-index-1;   if (nummoved = = 0)//delete just the last element     SetArray (arrays.copyof (elements, len-1));//Direct copy can complete the   else {     object[] newelements = new Object[len-1];     System.arraycopy (elements, 0, newelements, 0, index);//First half copy     system.arraycopy (elements, index + 1, newelements, index,nummoved)///second half copy     SetArray (newelements);//reset Array   }   return (E) oldvalue;//return deleted element} finally {   Lock.unlock ();//Release Lock}}
Delete Method Two

public boolean remove (Object o) {final Reentrantlock lock = This.lock;lock.lock (); try {object[] elements = GetArray ();    int len = elements.length; if (len! = 0) {int newlen = len-1;object[] newelements = new Object[newlen];//Set new array sizefor (int i = 0; i < Newlen; ++i) {if (eq (o, elements[i])) {//found one; Copy remaining and exitfor (int k = i + 1; k < Len; ++k)///Find one, then loop the back to the new array to complete this operationNewelements[k-1] = Elements[k];setarray (newelements);//Set new arrayreturn true; } Elsenewelements[i] = Elements[i];//No equal elements found}if (eq (o, Elements[newlen])) {//Judge whether the latter one is equalSetArray (newelements);//Set new arrayreturn true;} } return false;//If this element is not included, the contents of the original array are not changed .} finally {Lock.unlock ();} }


3, Get without lock

Public E get (int index) {return (E) (GetArray () [index]);//The data on the corresponding index of the array is returned, where it is possible that the original array is changed after the fetch is complete}final object[] GetArray () {return array;}

4, contains without lock
Public Boolean contains (Object o) {object[] elements = GetArray (); return indexOf (o, elements, 0, elements.length) >= 0; }private static int indexOf (Object o, object[] elements,int index, int fence) {if (o = = null) {for (int i = index; i < Fence i++) if (elements[i] = = null) return i;} else {for (int i = index; i < fence; i++) if (O.equals (Elements[i])) return i;} return-1;}

Second, Copyonwritearrayset source analysis

Copyonwritearrayset's principle scenario is the same as copyonwritearraylist, except that there is no duplicate element in it, it contains a copyonwritearraylist, and the method that is actually called It's a copyonwritearraylist method.

Data:

public class Copyonwritearrayset<e> extends abstractset<e> implements java.io.Serializable {private static Final long Serialversionuid = 5457747651344034263l;private final copyonwritearraylist<e> al; Contains only one copyonwritearraylist. }
You can see there's only one copyonwritearraylist. A member variable

Its main methods:

1. Add method

Public boolean Add (e e) {return al.addifabsent (e);//Call Copyonwritearraylist's Addifabsent method, if data returns false repeatedly, do not join}

2. Remove method
public boolean remove (Object o) {return al.remove (o);//Call the Remove method of Copyonwritearraylist}

3, Copyonwritearrayset No Get method, only through iterator to take
Public iterator<e> Iterator () {return al.iterator ();//Call Copyonwritearraylist's Iterator () method}
The Copyonwritearraylist iterator () method is as follows:
Public iterator<e> Iterator () {return new cowiterator<e> (GetArray (), 0);}
Where Cowiterator is an internal class of copyonwritearraylist, its main data structure is as follows:
private static class Cowiterator<e> implements Listiterator<e> {//array private final object[] snapshot;// The current pointer points to the array address private int cursor;private cowiterator (object[] elements, int initialcursor) {cursor = Initialcursor;snapshot = elements;} ..... }



Java Concurrency Programming and Technology Insider: Copyonwritearraylist, Copyonwritearrayset source analysis

Related Article

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.