HashMap vs concurrenthashmap-Example and iterator quest

Source: Internet
Author: User
Tags concurrentmodificationexception

If you are a Java developer, I can be sure you know concurrentmodificationexception, which is a (concurrent modification) exception caused by modifying a collection object when iterating through the collection object. In fact, the Java Collection Framework is a good implementation of the iterator design pattern.

Java 1.5 Introduces the Java.util.concurrent package, where the implementation of the collection class allows the collection object to be modified during the run. Concurrenthashmap is a class similar to HashMap, but it supports modifying collection objects at run time.

Let's use a simple program to help understand:

Package Com.king.hashmap;import Java.util.hashmap;import Java.util.iterator;import java.util.map;import java.util.concurrent.concurrenthashmap;/** * Concurrenthashmap can support adding new elements to map * HashMap throws the Concurrentmodificationexception */public class Concurrenthashmapexample {public static void main (string[] A        RGS) {//concurrenthashmap map<string, string> myMap = new concurrenthashmap<> ();        Mymap.put ("1", "1");        Mymap.put ("2", "1");        Mymap.put ("3", "1");        Mymap.put ("4", "1");        Mymap.put ("5", "1");        Mymap.put ("6", "1");        System.out.println ("Concurrenthashmap before iterator:" + myMap);        Iterator<string> it = Mymap.keyset (). Iterator ();            while (It.hasnext ()) {String key = It.next ();        if (Key.equals ("3")) Mymap.put (key + "new", "NEW3");        } System.out.println ("Concurrenthashmap after iterator:" + myMap);        HashMap MyMap = new hashmap<> (); Mymap.put ("1", "1");        Mymap.put ("2", "1");        Mymap.put ("3", "1");        Mymap.put ("4", "1");        Mymap.put ("5", "1");        Mymap.put ("6", "1");        System.out.println ("HashMap before iterator:" + myMap);        Iterator<string> it1 = Mymap.keyset (). Iterator ();            while (It1.hasnext ()) {String key = It1.next ();        if (Key.equals ("3")) Mymap.put (key + "new", "NEW3");    } System.out.println ("HashMap after iterator:" + myMap); }}

When we try to run the above program, the output is as follows:

ConcurrentHashMap before iterator: {1=1, 5=1, 6=1, 3=1, 4=1, 2=1}ConcurrentHashMap after iterator: {1=1, 3new=new3, 5=1, 6=1, 3=1, 4=1, 2=1}HashMap before iterator: {3=1, 2=1, 1=1, 6=1, 5=1, 4=1}Exception in thread "main" java.util.ConcurrentModificationException    at java.util.HashMap$HashIterator.nextEntry(HashMap.java:793)    at java.util.HashMap$KeyIterator.next(HashMap.java:828)    at com.test.ConcurrentHashMapExample.main(ConcurrentHashMapExample.java:44)

Looking at the output, it is clear that Concurrenthashmap can support adding new elements to the map, while HashMap throws the Concurrentmodificationexception.

Looking at the exception stack record, you can see that the following statement throws an exception:

String key = it1.next();

This means that the new element has been inserted in the HashMap, but an error occurred while the iterator was executing. In fact, the iterator for the collection object provides a mechanism for fast failure (fail-fast), that is, modifying the structure of the collection object or the number of elements will cause the iterator to trigger the exception.

But how does an iterator know that HashMap has been modified, and we can take all of the HashMap's keys and traverse them at once.

The HashMap contains a modifier counter that will be used by the iterator when you call its next () method to get the next element.

/** * HashMap结构的修改次数 * 结构修改是指:改变了HashMap中mapping的个数或者其中的内部结构(比如,重新计算hash值) * 这个字段在通过Collection操作Hashmap时提供快速失败(Fail-fast)功能。 * (参见 ConcurrentModificationException)。 */transient volatile int modCount;

Now to prove the point above, we make a little change to the original code so that the iterator jumps out of the loop after inserting the new element. Just add a break after calling the put method:

if(key.equals("3")){    myMap.put(key+"new", "new3");    break;}

After executing the modified code, you will get the following output:

ConcurrentHashMap before iterator: {1=1, 5=1, 6=1, 3=1, 4=1, 2=1}ConcurrentHashMap after iterator: {1=1, 3new=new3, 5=1, 6=1, 3=1, 4=1, 2=1}HashMap before iterator: {3=1, 2=1, 1=1, 6=1, 5=1, 4=1}HashMap after iterator: {3=1, 2=1, 1=1, 3new=new3, 6=1, 5=1, 4=1}

Finally, if we don't add new elements instead of modifying existing key-value pairs, will it throw an exception? Modify the original program and verify it yourself:

//myMap.put(key+"new", "new3");myMap.put(key, "new3");

After executing the modified code, you will get the following output:

ConcurrentHashMap before iterator: {1=1, 5=1, 6=1, 3=1, 4=1, 2=1}ConcurrentHashMap after iterator: {3new=new3, 1=1, 5=1, 6=1, 3=1, 4=1, 2=1}HashMap before iterator: {3=1, 2=1, 1=1, 6=1, 5=1, 4=1}HashMap after iterator: {3=new3, 2=1, 1=1, 6=1, 5=1, 4=1}

HashMap vs concurrenthashmap-Example and iterator quest

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.