I’m creating a multithread chat in java. When user u1 sends a message to user u2 but user u2 is not connected, user u1 sends the message to the server and user u2 will receive the message once he connects to the server. The messages who are not sent are added to an ArrayList. Once a user connects, he checks if he’s the recipient of a pending message. If he is, the message is sent to him and then removed from the pending messages list. This is how I do it:
for(Iterator<String> itpendingmsgs = pendingmsgs.iterator(); itpendingmsgs.hasNext();) {
String pendingmsg = itpendingmsgs.next();
String dest = pendingmsg.substring(4);
if (protocol.author.equals(dest)) {
sendMsg(msg);
pendingmsgs.remove(pendingmsg);
}
}
this is what I get:
Exception in thread "Thread-3" java.util.ConcurrentModificationException
at java.util.AbstractList$Itr.checkForComodification(Unknown Source)
at java.util.AbstractList$Itr.next(Unknown Source)
at ChatServer$ClientConnection.run(ChatServer.java:383)
at java.lang.Thread.run(Unknown Source)
How do I fix it? Is it because I’m using the iterator?
Instead of this
use
IteratorofArrayListis fail fast , so while you are iterating over theArrayListusing theIteratorif underlyingArrayListis modified by any method other thanaddandremoveprovided byIteratoritself it will throwConcurrentModificationExceptionand will bail out.In your current implementation while you are looping through the list on certain condition you are also modifying the list by calling
removeon the underlyingArrayList, instead callremovemethod of theIterator.From the Java Docs: