Home java How to handle the exclusion java.util.concurrentmodificationException?

How to handle the exclusion java.util.concurrentmodificationException?

Author

Date

Category

Have code: Link to Github . During the execution, the exception of Exception in Thread “AWT-EVENTQUEUE-0” java.util.concurrentmodificationException .
Knowing people tell me how to overcome the problem. Thanks in advance)


Answer 1, Authority 100%

it does not need to handle it. This exception means that you are in your code remove the item directly from the collection while using the iterator. Because In this case, uncertainty appears, from where the iterator must continue and what subsequent elements should pass, an exception is ejected. For correct entity change, use the methods of the iterator, for example, iterator.remove () .


Answer 2, Authority 16%

For example, you can put the lock before starting the ArrayList modification and remove the blocking after the completion of the modification. Use an uncompensable data structure ArrayList. Such a data structure will work correctly if the stream is one.

while (i.Hasnext ()) {
    Synchronized (I) {
      ENEMY E = I.NEXT ();
      if (E.X & GT; = 1600 || E.X & LT; = -1600) {
        i.Remove ();
      } else {
        E.Move (); // Put later
        g.drawimage (E.IMG, E.X, E.Y, NULL);
      }
    }
  }

In this code, blocking is removed later than the completion of the modification. You can rewrite the code:

while (i.Hasnext ()) {
    boolean isdrawimage = false;
    Synchronized (I) {
      ENEMY E = I.NEXT ();
      if (E.X & GT; = 1600 || E.X & LT; = -1600) {
        i.Remove ();
      } else {
        E.Move (); // Put later
        isDrawimage = True;
      }
    }
    if (isdrawimage)
      g.drawimage (E.IMG, E.X, E.Y, NULL);
  }

Answer 3

In addition to answer Etki I bring code for correct removal of the collection element inside the iterator cycle:

iterator & lt; string & gt; i = strings.iterator ();
While (i.Hasnext ()) {
  String Value = i.next (); // must be called before the i.Remove () is called
  // Some kind of code
  i.Remove (); // Element Value was removed from the Strings collection
}

Programmers, Start Your Engines!

Why spend time searching for the correct question and then entering your answer when you can find it in a second? That's what CompuTicket is all about! Here you'll find thousands of questions and answers from hundreds of computer languages.

Recent questions