1

I created the following code. My objective is to check the use of iterator to remove an element while reading the collection. Can anyone please explain why does a concurrentModificationException is thrown when collection of values of a hashmap is added to a linked list and after creating the iterator for that list, but the same is not thrown when the iterator is obtained after adding the collection to the list?

I know the reason would be very simple and would like something easily available, but yet I just want to confirm what I am thinking is correct or not.

There are 2 other points. 1. As hashmap is not threadsafe, so is it why, that we cant add any element to it while iterator is reading? 2. If yes, then how are we able to remove elements from the map?

 package com.Users;

import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;

    public class Temp{
        public static void main(String arg[]){
            HashMap<String, String> map=new HashMap();
            map.put("A", "B");
            map.put("C", "D");

            LinkedList<String> list=new LinkedList<>();

            //****** concurent exception is thrown when ever line 1 is swapped with line 2 ******
            Iterator<String> iterator=list.iterator();  //line no. 1
            list.addAll(map.values());    //line no. 2
            //******************

            while(iterator.hasNext()){
                if(iterator.next().equals("B")){
                    iterator.remove();
                }
            }


            System.out.println(list);
        }
    }
akshit bhatia
  • 573
  • 6
  • 22

1 Answers1

1

Iterator over HashMap is fail-fast in nature that essentially means they abort operation as-soon-as-possible exposing failures immediately.

Collections maintain an internal counter called modCount. Whenever an item is added or removed from the Collection, this counter gets modified.

When iterating, on each next() call, the current value of modCount gets compared with the initial value. If there’s a mismatch, it throws ConcurrentModificationException which aborts the entire operation.


  1. As hashmap is not threadsafe, so is it why that we can't add any element to it while the iterator is reading?

We can't modify the collection as we are iterating over the same because most of the Collections such as ArrayList, HashMap have fail-fast iterators by default.


  1. If yes, then how are we able to remove elements from the map?

We are able to remove elements in your example as we are using iterator's remove() method in iterator.remove(). If we would have used collection's remove() method, this would have thrown ConcurrentModificationException as well.

Do read this for detailed explaination.

Pramod
  • 1,376
  • 12
  • 21