Java. util. concurrentmodificationexception Solution

Source: Internet
Author: User

When iterator. hasnext () is used to operate on the iterator, if the iteration object changes at this time, such as inserting new data or deleting data.

The following exception is reported:
Java. util. concurrentmodificationexception
At java. util. hashmap $ hashiterator. nextentry (hashmap. Java: 793)
At java. util. hashmap $ keyiterator. Next (hashmap. Java: 828)

For example:Program(Transferred from the Internet ):

 
Mport Java. util. *; public class main {public static void main (string ARGs []) {main = new main (); main. test () ;}public void test () {map BB = new hashmap (); bb. put ("1", "WJ"); bb. put ("2", "ry"); iterator it = BB. keyset (). iterator (); While (it. hasnext () {object ele = it. next (); bb. remove (Ele); // wrong} system. out. println ("success! ");}}

Cause: When iterator performs traversal, hashmap is modified (BB. remove (Ele), size-1), iterator (Object ele = it. next () checks the size and size of the hashmap and throws the concurrentmodificationexception error.

Solution:

1) Modify hashtable through iterator
While (it. hasnext ()){
Object ele = it. Next ();
It. Remove ();
}

2) depending on the actual program, you can manually lock the program that iterator traverses and lock the program that modifies hashmap.

3) Replace hashmap with "concurrenthashmap". concurrenthashmap checks the modification operation and locks it. It can also be used for insert operations.
Import java. util. Concurrent .*;

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.