What is concurrent modification exception?

Concurrent modification exception:-This exception is occur when an object is modified concurrently while a Java Iterator is trying to loop through it.

				
					import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class ConcurrentException {
	public static void main(String[] args) {
		
		HashMap<Integer, String> h = new HashMap<Integer, String>();
		h.put(1, "hello");
		h.put(2, "good");
		h.put(3, "welcome");
		Iterator itr = h.keySet().iterator();
		while (itr.hasNext()) {
			System.out.println(h.get(itr.next()));
			h.put(4, "done");
		}
	}
}
				
			

Output :-
hello
Exception in thread “main”java.util.ConcurrentModificationException
at java.util.HashMap$HashIterator.nextNode(HashMap.java:1429)
at java.util.HashMap$KeyIterator.next(HashMap.java:1453)
at com.ConcurrentException.main(ConcurrentException.java:16)

how can I remove above exception :-
				
					import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class ConcurrentException {
	public static void main(String[] args) {
		
		ConcurrentHashMap<Integer, String> ch = new ConcurrentHashMap<Integer, String>();
		ch.put(1, "hello");
		ch.put(2, "welcome");
		ch.put(3, "Good");
		Iterator itr = ch.keySet().iterator();
		while (itr.hasNext()) {
			System.out.println(ch.get(itr.next()));
			ch.put(5, "done");
		}
	}
}
				
			

Output :-
hello
welcome
Good
Done

What is concurrent modification exception? Read More »