Synchronization set of new features in jdk5 (5)

Source: Internet
Author: User

1. Traditional collection:

In the traditional method, collection objects cannot be modified when the set is iterated:

public class CollectionModifyExceptionTest {public static void main(String[] args) {Collection<String> list = new ArrayList<String>();  list.add("aaa");list.add("bbb");list.add("ccc");Iterator<String> iter = list.iterator(); while (iter.hasNext()) {String str = (String) iter.next();if ("aaa".equals(str)) {list.remove(str);} else {System.out.println(str);}}}}

The following exception occurs:

Exception in thread "main" java.util.ConcurrentModificationExceptionat java.util.AbstractList$Itr.checkForComodification(AbstractList.java:372)at java.util.AbstractList$Itr.next(AbstractList.java:343)at com.zdp.thread.CollectionModifyExceptionTest.main(CollectionModifyExceptionTest.java:17)

2. Synchronization set:

JDK 5 provides the following synchronization collection classes:

Concurrenthashmap --> used under concurrent conditions. It inherits the same class as hashmap and adds a "Lock" to each method"

Copyonwritearraylist --> you can add or delete objects in a loop.

Copyonwritearrayset

public class CollectionModifyExceptionTest {public static void main(String[] args) {Collection<String> list = new CopyOnWriteArrayList<String>();  list.add("aaa");list.add("bbb");list.add("ccc");Iterator<String> iter = list.iterator(); while (iter.hasNext()) {String str = (String) iter.next();if ("aaa".equals(str)) {list.remove(str);} else {System.out.println(str);}}}}



Synchronization set of new features in jdk5 (5)

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.