Sunday

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.

Example:


OUTPUT
Key: 1
Exception in thread "Thread-0" java.util.ConcurrentModificationException
 at java.util.HashMap$HashIterator.nextEntry(Unknown Source)
 at java.util.HashMap$KeyIterator.next(Unknown Source)
 at jbohn.thread.JConcurentException$1.run(JConcurentException.java:26)
 at java.lang.Thread.run(Unknown 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) iterator.next();
   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>();


jbohn.blogspot.com

0 comments:

Post a Comment