Caught “Java. Util. Concurrentmodificationexception”

This is my code:

// eventList is a LinkedList

public void run() {

    Iterator<Event> it = eventList.iterator();
    int size = eventList.size();

    while(size > 0) {
        while(it.hasNext()) {
            Event e = it.next(); //flaged line

            if(e.ready()) {
                System.out.println(e);
                e.action();
                eventList.remove(e);
                --size;
            }
        }
    }
}

Bad Java util. Concurrentmodificationexception is thrown in the marked line (event E = it. Next();) Do you see an error in my code that is obviously the reason for throwing an exception?

Solution

You use eventlist when iterating Remove() modifies eventlist You cannot do this, otherwise the iterator will become unusable

Just use it Remove() replaces eventlist Just remove (E)

In addition, if one of your events is not ready in the first run, you can easily encounter infinite loops because it Once hasnext () returns false, it will never return true, but it will not change the size One solution is to move the entire iterator it =... Line into the first while loop

I also modified the external while loop to use while (! E.isempty()) instead of trying to track the size of the eventlist manually

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>