Example of "ConcurrentModificationException" in multithreading and How to avoid?

When this exception happen?
This exception when a collection is modifying when it's being traversed.


Key: 1
Exception in thread "Thread-0" java.util.ConcurrentModificationException
 at java.util.HashMap$HashIterator.nextEntry(Unknown Source)
 at java.util.HashMap$ Source)
 at jbohn.thread.JConcurentException$
 at Source)
Avoid this problem:
1. Clone a temporary list when loop a collection. This option work well for small list, but performance is affected.
//Copy key set to new list
ArrayList<Integer> keyList = new ArrayList<>(maps.keySet());
for (Iterator iterator = keyList.iterator(); iterator.hasNext();) {
   Integer integer = (Integer);
   System.out.println("Key: " + integer);

2. Using ConcurrentHashMap and CopyOnWriteArrayList for JDK 1.5 and above
private static final Map<Integer, String> maps = new ConcurrentHashMap<Integer, String>();


Post a Comment