我正在用java創建一個多線程聊天服務器。 當用戶u1登錄並向用戶u2發送消息時,如果用戶u2未連接,則將消息發送到服務器並放入待處理消息的ArrayList。當用戶u2連接時,他從服務器接收消息並將消息作爲收據發送給用戶u1。ConcurrentModificationException異常與迭代器在mutithread聊天服務器
這是我的代碼:
if (pendingmsgs.size()>0) {
for(Iterator<String> itpendingmsgs = pendingmsgs.iterator(); itpendingmsgs.hasNext();) {
//....parsing of the message to get the recipient, sender and text
String pendingmsg = itpendingmsgs.next();
if (protocol.author != null && protocol.author.equals(recipient)) {
response+=msg;
protocol.sendMsg(sender, "Msg "+text+" sent to "+recipient);
itpendingmsgs.remove();
}
}
}
out.write(response.getBytes(), 0, response.length());
這是ServerProtocol SENDMSG()方法:
private boolean sendMsg(String recip, String msg) throws IOException {
if (nicks.containsKey(recip)) { //if the recipient is logged in
ClientConnection c = nick.get(recipient); //get the client connection
c.sendMsg(msg); //sends the message
return true;
} else {
/* if the recipient is not logged in I save the message in the pending messages list */
pendingmsgs.add("From: "+nick+" to: "+recip+" text: "+msg);
return false;
}
}
這就是ClientConnection SENDMSG()方法:
public void sendMsg(String msg) throws IOException {
out.write(msg.getBytes(), 0, msg.length());
}
其中out是一個OutputStream。
當用戶U1登錄時,將消息發送到用戶U2誰不在,然後用戶U1葉登錄,當他用戶U2日誌沒有收到消息,我得到這個異常:
Exception in thread "Thread-2" java.util.ConcurrentModificationException
at java.util.AbstractList$Itr.checkForComodification(Unknown Source)
at java.util.AbstractList$Itr.remove(Unknown Source)
at ChatServer$ClientConnection.run(ChatServer.java:400)
at java.lang.Thread.run(Unknown Source)
400線是
itpendingmsgs.remove();
我使用的CopyOnWriteArrayList嘗試,但它仍然無法正常工作。
哪一條是400線? – Tudor
對不起,第400行是itpendingmsgs.remove(); –