The problem of the traditional collection class in concurrent access and the synchronization collection class provided by Java5 __java

Source: Internet
Author: User
Tags concurrentmodificationexception
It programmer development must-all kinds of resources download list, the most complete IT resources in history, personal collection summary.
1. The traditional collection class in the concurrent access problem description, see example program
2. In the traditional way, the Synchronizedcollection method provided by the Collections tool class is used to obtain the synchronized set, and the realization source of the method is analyzed.
3. Collection in the traditional way the collection is not allowed to be modified when iterating over the collection.
(1) Using the Air network interview synchronization level thread problem to demonstrate
(2) According to the source code of Abstractlist's Checkforcomodification method, analyze the cause of concurrentmodificationexception anomaly.
(3) Some of the following synchronization collection classes are available in JAVA5:
4. By looking at the introduction of the Java.util.concurrent package, you can know what concurrent collections
(1) Concurrenthashmap
(2) Copyonwritearraylist
(3) Copyonwritearrayset

Example Program:

package edu.java5.util; import java.util.ArrayList; import java.util.Collection; import
Java.util.Iterator;
Import java.util.concurrent.CopyOnWriteArrayList; public class Collectionmodifyexception {public static void main (string[] args) {//change ArrayList to Copyonwritearraylist, no
		The following conditions will appear Collection users = new ArrayList ();
		Collection users = new Copyonwritearraylist ();	
		Users.add (New User ("John", 28));			
		Users.add (New User ("Dick", 25));	
		Users.add (New User ("Harry", 31));
		Iterator itrusers = Users.iterator ();
			while (Itrusers.hasnext ()) {User user = (User) itrusers.next (); 
				 if ("John". Equals (User.getname ())) {//code 1/** * Note that comparing the two differences * users.remove (user) Actions can cause exceptions and the data in the collection is deleted  * Itrusers.remove () operation does not cause an exception, the data in the collection is deleted **/users.remove (user); Code 2//itrusers.remove ();				
			Code 3} else {System.out.println (user);
	} System.out.println (Users.size ()); }
}	 

(1) Code 1 is if ("John". Equals (User.getname ()) {executes:

Exception in thread "main" java.util.ConcurrentModificationException
At Java.util.abstractlist$itr.checkforcomodification (abstractlist.java:372)
At Java.util.abstractlist$itr.next (abstractlist.java:343)
At Edu.java5.util.CollectionModifyException.main (collectionmodifyexception.java:16)
(2) Code 1 is if ("Dick". Equals (User.getname ()) {executes:

{name: ' John ', age:28}
2
(3) Code 1 is if ("Harry". Equals (User.getname ()) {executes:
{name: ' John ', age:28}
{name: ' Dick ', age:25}
Exception in thread "main" java.util.ConcurrentModificationException
At Java.util.abstractlist$itr.checkforcomodification (abstractlist.java:372)
At Java.util.abstractlist$itr.next (abstractlist.java:343)
At Edu.java5.util.CollectionModifyException.main (collectionmodifyexception.java:16)

(4) Comment out Code 2 and remove the comment execution of code 3:

{name: ' John ', age:28}
{name: ' Dick ', age:25}
2

(1) (2) (3) The cause of the abnormal phenomenon:

 Private class Itr implements iterator<e> {/** * Index of element to is returned by subsequent call to next.                     */INT cursor = 0;  Code/** * Index of element returned by most recent call to next or * previous.
	 Reset To-1 If this element was deleted by a call * to remove.

	*/INT lastret =-1;  /** * The Modcount value that the iterator believes this backing * List should have.
	 If this expectation is violated, the iterator * has detected concurrent.      * * int expectedmodcount = Modcount;           Code public boolean Hasnext () {return cursor!= size ();
	    Code} public E next () {checkforcomodification ();
		try {E next = get (cursor);             Lastret = cursor++;
	    Code return next;
		catch (Indexoutofboundsexception e) {checkforcomodification ();
	    throw new Nosuchelementexception (); } public void Remove () {if (Lastret = 1) throw new illegalstateexceptIon ();          Checkforcomodification ();
		Code try {AbstractList.this.remove (Lastret);
		if (Lastret < cursor) cursor--;
		Lastret =-1;
	    Expectedmodcount = Modcount;
	    catch (Indexoutofboundsexception e) {throw new concurrentmodificationexception (); } final void Checkforcomodification () {if (Modcount!= expectedmodcount)//code throw new Concur
	Rentmodificationexception (); }
    }




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.