Android multi-threaded----Sync Collection

Source: Internet
Author: User

First, the optimization strategy in the program--copyonwritearraylist
Copy-on_write is a kind of optimization strategy used in program design, the basic idea of the device is:
The same list is shared from multiple threads, and when a thread wants to modify the elements of the list, it copies the elements of the list, then modifies them, and after the modification is done, it is a lazy strategy to set the new element to the list. The advantage of this is that we can read the Copyonwrite container concurrently, not lock it, because the current container is not added and any elements are removed. So the Copyonwrite container is a read and write separation of ideas, reading and writing different containers.
Here is the Add method for Copyonwritearraylist:

 public  boolean add  (E 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 (); }    }

From the program can be found, at the time of the addition of the lock operation, responsible for multi-threaded writing will be copied out n copies out, copy the new elements added after the set to the Len position of the element array, after dinner, the latest element array set to the list.
There is no need to lock when reading, and if multiple threads are adding data to copyonwritearraylist at the time of reading, the data will still be read, because the old element data will not be locked when writing.
The Get method is as follows:

    publicget(int index) {        returnget(getArray(), index);    }

and a similar copyonwirtearrayset.

Second, improve the concurrency efficiency ———-concurrenthashmap
Using lock segmentation technology, each lock is used to lock the container part of the data, then when the multi-threaded access to different data segments, there will be no lock competition between the county, which can effectively improve the efficiency of concurrent access.
Attach a put, get method, where segment is a data segment

 PublicVput(K key, Vvalue) {segment<k,v> s;if(value==NULL)Throw NewNullPointerException ();inthash = hash (key);intj = (hash >>> segmentshift) & Segmentmask;if((s = (segment<k,v>) unsafe.getobject//nonvolatile; recheck(Segments, (J << Sshift) + sbase)) ==NULL)//In Ensuresegments = ensuresegment (j);returnS.put (key, hash,value,false); } PublicVGet(Object key) {segment<k,v> s;//Manually integrate access methods to reduce overheadhashentry<k,v>[] tab;intH = hash (key);LongU = (((H >>> segmentshift) & Segmentmask) << sshift) + sbase;if((s = (segment<k,v>) unsafe.getobjectvolatile (segments, u))! =NULL&& (tab = s.table)! =NULL) { for(hashentry<k,v> e = (hashentry<k,v>) unsafe.getobjectvolatile (tab, (Long) ((Tab.length-1) & H)) << Tshift) + tbase); E! =NULL; E = E.next) {k k;if(k = e.key) = = Key | | (E.hash = = h && key.equals (k)))returnE.value; }        }return NULL; }

Third, blocking queue--–blockingqueue
Blocking queues provide features such as calling the Put function to add elements again when the queue is full, and the calling thread will block until the queue is no longer filled. This feature is very useful, it is the producer-consumer a realization.

Add (E): Adds element e to Blockingqueue, or returns True if Blockingqueue can accommodate, otherwise throws an exception.

Offer (E): The element e is added to the Blockingqueue, if the blockingqueue can be accommodated, returns True, otherwise false.

Offer (E,time,unit): Adds element e to Blockingqueue, returns true if Blockingqueue can accommodate, or waits for the specified blockingqueue to continue adding.

Put (E): add element E to Blockingqueue, if Blockingqueue cannot accommodate, the thread calling this method is blocked until Blockingqueue has space to continue adding.

Take () takes the blockingqueue of the line in the first row of the object, if the Blockingqueue is empty, then enter the waiting state until blocking a new object to join.

Poll (Time,unit): Remove and remove the first element of the queue and return NULL if no data has been obtained within the set blocking time.

Element (): Gets the first element of the team and throws a Nosuchelementexception exception if the queue is empty.

Peek (): Gets the first element of the team and returns null if the queue is empty

Remove (): Gets and removes the first element of the team and throws a Nosuchelementexception exception if the queue is empty.

The main implementations are:
Arrayblockingqueue an array-implemented, thread-safe, bounded blocking queue.
Linkedblockingqueue a blocking queue implemented by a unidirectional list that arranges elements in a FIFO and inserts new elements into the tail of the queue.
Linkedblockingdeque bidirectional concurrent blocking queue implemented by a doubly-linked list that supports both FIFO and filo two modes of operation.
There is also Concurrentlinkedqueue, a secure queue with no boundaries based on link nodes.

Android multi-threaded----Sync Collection

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.