Are you getting ConcurrentModification Exception in Java? How to fix it? Mainly this happens when you try to remove element from ArrayList while iterating through it.
We usually get this exception in multithreading environment in production.
Here is a complete Java Exception Stack trace.
/Users/app/Library/Java/JavaVirtualMachines/openjdk-17.0.1/Contents/Home/bin/java --enable-preview -javaagent:/Applications/IntelliJ IDEA.app crunchify.com.java.tutorials.CrunchifyConcurrentModificationException Exception in thread "main" java.util.ConcurrentModificationException at java.base/java.util.ArrayList$Itr.checkForComodification(ArrayList.java:1013) at java.base/java.util.ArrayList$Itr.next(ArrayList.java:967) at crunchify.com.java.tutorials.CrunchifyConcurrentModificationException.main(CrunchifyConcurrentModificationException.java:27) Process finished with exit code 1
Let’s first reproduce Concurrent Modification Exception.
CrunchifyConcurrentModificationException.java
package crunchify.com.java.tutorials; import java.util.ArrayList; import java.util.List; /** * @author Crunchify.com * What is ConcurrentModification Exception in Java? How to fix it? */ public class CrunchifyConcurrentModificationException { public static void main(String[] args) { // ArrayList(): Constructs an empty list with an initial capacity of ten. List<String> crunchifyList = new ArrayList<>(); // add(): Appends the specified element to the end of this list (optional operation). // Lists that support this operation may place limitations on what elements may be added to this list. // In particular, some lists will refuse to add null elements, // and others will impose restrictions on the type of elements that may be added. // List classes should clearly specify in their documentation any restrictions on what elements may be added. crunchifyList.add("Google.com"); crunchifyList.add("Crunchify.com"); crunchifyList.add("Facebook.com"); crunchifyList.add("Apple.com"); for (String crunchifyListElement : crunchifyList) { // equals(): Compares this string to the specified object. // The result is true if and only if the argument is not null and is a String object that represents the same sequence of characters as this object. // For finer-grained String comparison, refer to java.text.Collator. if ("Apple.com".equals(crunchifyListElement)) { // remove(): Removes the first occurrence of the specified element from this list, if it is present (optional operation). crunchifyList.remove(crunchifyListElement); } } System.out.println(crunchifyList); } }
Just run above Java Program as Java application and you will be able to generate error.
How to fix Concurrent Modification Exception?
Here is a complete example and 5 different ways to avoid
ConcurrentModification Exception.Let me know if you face any issue running above program.
The post How to avoid ConcurrentModification Exception in a multi-threaded environment? appeared first on Crunchify.
0 Commentaires