gpt4 book ai didi

java - 多线程聊天服务器中迭代器出现 ConcurrentModificationException 异常

转载 作者:行者123 更新时间:2023-12-02 07:46:53 26 4
gpt4 key购买 nike

我正在用 java 创建一个多线程聊天服务器。当用户 u1 登录并向用户 u2 发送消息时,如果用户 u2 未连接,则消息将发送到服务器并放入待处理消息的 ArrayList 中。当用户u2连接时,他接收来自服务器的消息,并将消息发送给用户u1作为回执。

这是我的代码:

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 是一个输出流。

当用户 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 但它仍然不起作用。

最佳答案

CopyOnWriteArrayList.iterator() doesn't support remove() 。您可能应该使用 Collections.synchronizedList(ArrayList) (按照 Javadoc 中的规定,在迭代期间正确锁定)。

这确实是允许一个线程添加到列表而另一个线程迭代删除元素的最简单方法。

关于java - 多线程聊天服务器中迭代器出现 ConcurrentModificationException 异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10707161/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com