gpt4 book ai didi

java - arraylist并发修改

转载 作者:行者123 更新时间:2023-12-01 16:34:36 24 4
gpt4 key购买 nike

我正在用 java 创建多线程聊天。当用户u1向用户u2发送消息,但用户u2未连接时,用户u1将消息发送到服务器,用户u2连接到服务器后就会收到该消息。未发送的消息将添加到 ArrayList 中。用户连接后,他会检查自己是否是待处理消息的收件人。如果是,则消息将发送给他,然后从待处理消息列表中删除。我就是这样做的:

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);
}
}

这就是我得到的:

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)

如何修复它?是因为我使用了迭代器吗?

最佳答案

而不是这个

pendingmsgs.remove(pendingmsg);

使用

itpendingmsgs.remove();

IteratorArrayList fail fast ,因此当您迭代 ArrayList 时使用Iterator如果底层 ArrayList通过 add 以外的任何方法修改和removeIterator提供它本身会抛出 ConcurrentModificationException并将退出。

在当前的实现中,当您在某些条件下循环列表时,您还可以通过调用remove来修改列表。底层ArrayList ,而是调用 remove Iterator的方法.

来自 Java 文档:

The iterators returned by this class's iterator and listIterator methods are fail-fast: if the list is structurally modified at any time after the iterator is created, in any way except through the iterator's own remove or add methods, the iterator will throw a ConcurrentModificationException. Thus, in the face of concurrent modification, the iterator fails quickly and cleanly, rather than risking arbitrary, non-deterministic behavior at an undetermined time in the future.

Note that the fail-fast behavior of an iterator cannot be guaranteed as it is, generally speaking, impossible to make any hard guarantees in the presence of unsynchronized concurrent modification. Fail-fast iterators throw ConcurrentModificationException on a best-effort basis. Therefore, it would be wrong to write a program that depended on this exception for its correctness: the fail-fast behavior of iterators should be used only to detect bugs.

关于java - arraylist并发修改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10690903/

24 4 0