How to Resolve java util ConcurrentModificationException in Java

java.util.ConcurrentModificationException

In this example, we will show you how to resolve the java util ConcurrentModificationException in java. The example program were tested with environment and output has been shared in the same post.

1) When it will happen?

Output with following error.

[null, 1, 3]Exception in thread “2”
[null, 1, 3] java.util.ConcurrentModificationException
at java.util.ArrayList$Itr.checkForComodification(Unknown Source)
at java.util.ArrayList$Itr.next(Unknown Source)
at java.util.AbstractCollection.toString(Unknown Source)[null, 1, 3, 4] at java.lang.String.valueOf(Unknown Source)

at java.io.PrintStream.println(Unknown Source)
at com.dineshkrish.ListAppender.run(ListAppender.java:18)
at java.lang.Thread.run(Unknown Source)
[null, 1, 3, 4, 5] [null, 1, 3, 4, 5, 6] [null, 1, 3, 4, 5, 6, 9, 8] Exception in thread “9” [null, 1, 3, 4, 5, 6, 9, 8, 7] java.util.ConcurrentModificationException
[null, 1, 3, 4, 5, 6, 9, 8, 7, 10] at java.util.ArrayList$Itr.checkForComodification(Unknown Source)
at java.util.ArrayList$Itr.next(Unknown Source)
at java.util.AbstractCollection.toString(Unknown Source)
at java.lang.String.valueOf(Unknown Source)
at java.io.PrintStream.println(Unknown Source)
at com.dineshkrish.ListAppender.run(ListAppender.java:18)
at java.lang.Thread.run(Unknown Source)

2) Resolving the java util ConcurrentModificationException

The CopyOnWriteArrayList will allow the concurrent modification among the multiple thread, by changing the ArrayList object to CopyOnWriteArrayList. We can able to resolve the java util ConcurrentModificationException in java.

Output

[2, 1] [2, 1, 3] [2, 1] [2, 1, 3, 5] [2, 1, 3, 5, 7] [2, 1, 3, 5, 7, 4] [2, 1, 3, 5, 7, 4, 6] [2, 1, 3, 5, 7, 4, 6, 10] [2, 1, 3, 5, 7, 4, 6, 10, 9] [2, 1, 3, 5, 7, 4, 6, 10, 9, 8]

References

1. Java List Interface
2. Java ArrayList Class
3. Java CopyOnWriteArrayList Class
4. Java Runnable Interface
5. Java Thread Class