Java multi-threading and concurrent libraries Advanced applications-synchronizing collections

Source: Internet
Author: User

Arrayblockingqueue

Linkedblockingqueue

Array is a contiguous piece of memory

A linked list is a discontinuous piece of memory

In the traditional way, the Synchronizedcollection method provided by the Collections tool class is used to obtain the synchronous Collection.

Some of the following synchronization collection classes are available in Java5:

> by looking at the introduction under the Java.util.concurrent package, you can know which concurrent collections

> Concurrenthashmap

> copyonwritearraylist

> Copyonwritearrayset

The collection in the traditional way is not allowed to modify the collection at Iteration Time.

You cannot modify a collection when iterating over a collection using iterator

 public classCollectionmodifyexceptiontest { public Static voidmain (string[] Args) {List<String> STRs =NewArraylist<>(); Strs.add ("aaa"); Strs.add ("bbb"); Strs.add ("ccc"); Iterator Iterator=Strs.iterator ();  while(iterator.hasnext ()) {System.out.println ("....."); String value=(String) Iterator.next (); if("aaa". Equals (value))            {strs.remove (value); }Else{System.out.println (value); }        }    }}

The above code, when traversing the collection, modifies the collection and throws an exception

Exception in thread "main" java.util.ConcurrentModificationException
At Java.util.arraylist$itr.checkforcomodification (arraylist.java:859)
At Java.util.arraylist$itr.next (arraylist.java:831)
At Com.java.thread.CollectionModifyExceptionTest.main (collectionmodifyexceptiontest.java:17)

Exception thrown in this sentence

String value = (string) iterator.next ();
/*** An optimized version of Abstractlist.itr*/    Private classItrImplementsIterator<e> {        intCursor//index of next element to return        intLastret =-1;//index of last element returned;-1 if no such        intExpectedmodcount =modcount;  public Booleanhasnext () {//returncursor! =size; } @SuppressWarnings ("unchecked")         publicE next () { checkforcomodification (); inti =cursor; if(i >=Size)Throw Newnosuchelementexception (); object[] Elementdata= ArrayList. this. elementdata; if(i >=Elementdata.length)Throw Newconcurrentmodificationexception (); Cursor= i + 1; return(E) Elementdata[lastret =i]; }         public voidRemove () {if(lastret < 0)                Throw Newillegalstateexception ();            Checkforcomodification (); Try{ArrayList. this. Remove (lastret); Cursor=lastret; Lastret=-1; Expectedmodcount=modcount; } Catch(indexoutofboundsexception Ex) {Throw Newconcurrentmodificationexception (); }        }        final void checkforcomodification () {if (modcount! = expectedmodcount) throw new concurrentmodificationexception ();//throw exception here} }

however, when the "aaa" is changed to "bbb", it does not throw an exception

Because the cursor is 1 (0,1,2) when traversing to bbb, the next traversal after the BBB is removed after the size is 2 is the cursor 2

So Hasnext () returns false and does not enter the Loop.

To solve this problem, you can use copyonwritearraylist to have a copy when writing,

 public Static voidmain (string[] Args) {List<String> STRs =Newcopyonwritearraylist (); Strs.add ("aaa"); Strs.add ("bbb"); Strs.add ("ccc"); Iterator Iterator=Strs.iterator ();  while(iterator.hasnext ()) {System.out.println ("....."); String value=(String) Iterator.next (); if("aaa". Equals (value))            {strs.remove (value); }Else{System.out.println (value); }        }    }

Java multi-threading and concurrent libraries Advanced applications-synchronizing collections

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.