How To Bargain Alongside Concurrentmodificationexception Inwards Java? Beware Spell Removing Elements From Arraylist Inwards Loop

One of the mutual work piece removing elements from an ArrayList inward Java is the ConcurrentModificationException. If you lot purpose classical for loop alongside the index or enhanced for loop as well as endeavour to take an chemical cistron from the ArrayList using remove() method, you lot volition acquire the ConcurrentModificationException but if you lot purpose Iterator's take method or ListIterator's remove() method, so you lot won't acquire this mistake as well as endure able to take the element. It's an unwritten dominion inward Java that piece looping through the list, you lot should non add() or remove() elements until the collection supports fail-safe Iterator e.g. CopyOnWriteArrayList, which operate on a re-create of listing rather than the master copy list.

The primary work alongside this mistake is that it confuses developer that listing is getting modified past times multiple threads as well as that's why Java is throwing this error, it's non true. Most of the fourth dimension ConcurrentModificationException comes fifty-fifty without multiple threads modifying the list.

It's misnomer, don't acquire fooled away past times this. though it seems natural thinking that perchance approximately other thread is trying to alteration the collection at the same time, it's ordinarily breaking the Java rule.

In this article, I'll explicate this mistake as well as we'll many code event to reproduce this code fifty-fifty alongside the unmarried thread as well as larn how nosotros tin avoid concurrent modification mistake piece modifying an ArrayList inward Java.

Btw, if you lot are non familiar alongside collection classes e.g. ArrayList itself so you lot should bring together an online class e.g. Java Basics: Learn to Code the Right Way on Udemy is a skilful house to start with.



ConcurrentModificationException inward Single Thread

This is the kickoff event of reproducing the concurrent modification exception inward Java. In this program, nosotros are iterating over ArrayList using the enhanced foreach loop as well as removing selective elements e.g. an chemical cistron which matches surely status using ArrayList's remove method.

For example, inward the below code nosotros receive got kickoff added a distich of skilful programming books e.g. Programming Pearls, Clean Code, Effective Java, as well as Code Complete into ArrayList as well as so removing whatever chemical cistron which has Code inward its title.

package beginner;  import java.util.ArrayList; import java.util.List;  public class HelloWorldApp{     public static void main(String... args){        List<String> listOfBooks = new ArrayList<>();          listOfBooks.add("Programming Pearls");        listOfBooks.add("Clean Code");        listOfBooks.add("Effective Java");        listOfBooks.add("Code Complete");                // Using forEach loop to iterate as well as removing         // chemical cistron during iteration volition throw         // ConcurrentModificationException inward Java        for(String book: listOfBooks){            if(book.contains("Code"));{                listOfBooks.remove(book);            }        }    }  } Output Exception in thread "main" java.util.ConcurrentModificationException     at java.util.ArrayList$Itr.checkForComodification(Unknown Source)     at java.util.ArrayList$Itr.next(Unknown Source)     at beginner.HelloWorldApp.main(HelloWorldApp.java:18)


You tin run into that this mistake comes fifty-fifty though nosotros only receive got i thread, primary thread which is operating alongside ArrayList. The ConcurrentModification mistake comes because nosotros are non using Iterator, instead only calling listOfBooks.remove() method.

In this code, I receive got used Java 1.5 enhanced for loop, you lot must know how enhanced for loop industrial plant inward Java.

Difference betwixt for loop as well as enhanced for loop is that subsequently internally uses an Iterator for going over all elements of a collection. For a to a greater extent than in-depth discussion, run into here



Using Classical for loop as well as ArrayList.remove(index)

Here is approximately other interesting code event of removing elements from ArrayList. Surprisingly this code volition non throw ConcurrentModificationException when you lot kickoff run it? make you lot know why?

Well, endeavour it earlier you lot facial expression at the explanation after the code. It's truly this sort of fry details close Java programming linguistic communication as well as Collection framework, which volition brand you lot a skilful developer, as well as likewise assistance you lot to acquire your Java certification if you lot are preparing for it.

package beginner;  import java.util.ArrayList; import java.util.List;  public class HelloWorldApp{     public static void main(String... args){        List<String> listOfBooks = new ArrayList<>();          listOfBooks.add("Programming Pearls");        listOfBooks.add("Clean Code");        listOfBooks.add("Effective Java");        listOfBooks.add("Code Complete");                System.out.println("List earlier : " + listOfBooks);        for(int i=0; i<listOfBooks.size(); i++){            String mass = listOfBooks.get(i);            if(book.contains("Programming")){                System.out.println("Removing " + book);                listOfBooks.remove(i); // volition throw CME            }        }        System.out.println("List after : " + listOfBooks);    }  }  Output List earlier : [Programming Pearls, Clean Code, Effective Java, Code Complete] Removing Programming Pearls List after : [Clean Code, Effective Java, Code Complete]

This code doesn't throw ConcurrentModificationException because hither nosotros are not using Iterator but nosotros are only using traditional for loop.

It's the Iterator which throws ConcurrentModificationException, as well as non the take method of ArrayList, thus you lot don't run into that mistake inward below code.

If you lot facial expression at the code for ArrayList.java, you lot volition notice that at that topographic point is a nested degree which implemented Iterator interface as well as it's next() method calls checkForComodification() component subdivision which truly checks if ArrayList has modified during iteration or not, if modCount doesn't fit alongside expectedModCount so it throws ConcurrentModificationException.

final void checkForComodification() {   if (modCount != expectedModCount)     throw new ConcurrentModificationException(); }

This sort of questions are likewise real pop on Oracle Java Certification e.g. OCAJP (1z0-808) as well as OCPJP (1Z0-809), so if you lot are preparing for those exams, you lot should know the answer.

Here is the sum code snippet from the ArrayList.java degree for your quick reference:

 One of the mutual work piece removing elements from an ArrayList inward Java is the Concur How to bargain alongside ConcurrentModificationException inward Java? Beware piece removing elements from ArrayList inward loop


Using Iterator but ArrayList's take method

Now, let's run into approximately other code example, where Java programmer thinks he has done everything correct but nevertheless getting the concurrent modification exception. Can you lot spot the error? It's truly mutual as well as I receive got seen this sort of code a lot of fourth dimension on Java forums, StackOverflow as well as on Facebook Java groups where they asked to prepare the problem.

package beginner;  import java.util.ArrayList; import java.util.Iterator; import java.util.List;  public class HelloWorldApp{     public static void main(String... args){        List<String> listOfBooks = new ArrayList<>();          listOfBooks.add("Programming Pearls");        listOfBooks.add("Clean Code");        listOfBooks.add("Effective Java");        listOfBooks.add("Code Complete");                Iterator<String> iterator = listOfBooks.iterator();        while(iterator.hasNext()){            String mass = iterator.next();            listOfBooks.remove(book);        }    }  }  Output Exception in thread "main" java.util.ConcurrentModificationException     at java.util.ArrayList$Itr.checkForComodification(Unknown Source)     at java.util.ArrayList$Itr.next(Unknown Source)     at beginner.HelloWorldApp.main(HelloWorldApp.java:18)

The existent work alongside this code is that fifty-fifty though the code is using Iterator to become over ArrayList, it's non truly using the Iterator.remove() method to take the element. It is only using Iterator to acquire the side past times side chemical cistron but calling the ArrayList.remove() method to delete the element.

I know, it looks slow when you lot know the argue but inward existent time, many times programmer receive got fifty-fifty hours to figure out what is wrong. So, only beware of that.

Btw, if you lot are learning Java so I propose joining Complete Java Masterclass to larn Java meliorate as well as avoid such mutual errors.

 One of the mutual work piece removing elements from an ArrayList inward Java is the Concur How to bargain alongside ConcurrentModificationException inward Java? Beware piece removing elements from ArrayList inward loop


Right means to take chemical cistron is past times using Iterator's take method

Finally, hither is the correct means to delete an chemical cistron from ArrayList during iteration. In this example, nosotros receive got used Iterator both iterate equally good equally take the element. The code is ok but it has a serious limitation, you lot tin alone purpose this code to take the electrical flow element. You cannot take whatever arbitrary chemical cistron from ArrayList inward Java.

package beginner;  import java.util.ArrayList; import java.util.Iterator; import java.util.List;  public class HelloWorldApp{     public static void main(String... args){        List<String> listOfBooks = new ArrayList<>();          listOfBooks.add("Programming Pearls");        listOfBooks.add("Clean Code");        listOfBooks.add("Effective Java");        listOfBooks.add("Code Complete");                System.out.println("List earlier : " + listOfBooks);        Iterator<String> iterator = listOfBooks.iterator();        while(iterator.hasNext()){            String mass = iterator.next();            System.out.println("Removing " + book);            iterator.remove();        }        System.out.println("List after : " + listOfBooks);    }  } Output List earlier : [Programming Pearls, Clean Code, Effective Java, Code Complete] Removing Programming Pearls Removing Clean Code Removing Effective Java Removing Code Complete List after : []

The same deportment is applicable to ListIterator equally well. I hateful you lot tin supersede Iterator alongside ListIterator as well as code volition travel fine. The ListIterator likewise allow you lot to navigate inward both directions i.e. forwards as well as backward.

That's all close how to avoid ConcurrentModificationException piece removing elements from ArrayList during iteration. You tin purpose the same technique to avoid ConcurrentModificationException piece removing elements from whatever other collection classes which receive got fail-fast Iterator e.g. LinkedList. Btw, if you lot are novel to Java programming so joining a good, comprehensive class like Java Basics: Learn to Code the Right Way on Udemy tin assistance you lot to larn Java meliorate as well as quicker.

Other Java troubleshooting Guides you lot may like
How to solve ArrayIndexOutOfBoundsException inward Java? (guide)
How to solve NullPointerException inward Java? (guide)
How to solve the "System cannot notice the Path specified" error? (solution)
How to solve NoClassDefFoundError piece running Java programme from a ascendance line? (solution)
How to solve "No JVM found, Please install 64-bit JDK" mistake inward Android Studio? (solution)
How to bargain alongside SQLException "No Suitable driver constitute " mistake inward JDBC as well as MySQL? (guide)
How to solve NumberFormatException inward Java? (guide)
How to solve Minecraft - java.lang.UnsatisfiedLinkError: lwjgl64.dll : Access Denied? (solution)
How to prepare java.lang.ArrayIndexOutOfBoundsException: 1 inward Java? (solution)
How to prepare java.net.SocketException: Software caused connectedness abort: recv failed (fix)

Thanks for reading this tutorial, if you lot similar this tutorial so delight part alongside your friends as well as colleagues.  If you lot receive got whatever enquiry or proffer so delight drib a comment. 

Sumber https://javarevisited.blogspot.com/

0 Response to "How To Bargain Alongside Concurrentmodificationexception Inwards Java? Beware Spell Removing Elements From Arraylist Inwards Loop"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel