gpt4 book ai didi

ArrayList 上的 java.util.ConcurrentModificationException

转载 作者:搜寻专家 更新时间:2023-11-01 01:02:31 26 4
gpt4 key购买 nike

我有一个 Server 类和一个 Timer,它应该清除死掉的客户端(崩溃的客户端)。我按照下面的示例在 Timer 遍历用户时锁定集合,但我仍然遇到此异常(在我使连接的客户端崩溃之后)。

http://www.javaperformancetuning.com/articles/fastfail2.shtml

List<User> users;
List<User> connectedUsers;
ConcurrentMap<User, IClient> clients;

...

users = Collections.synchronizedList(new ArrayList<User>());
connectedUsers = new ArrayList<User>();
clients = new ConcurrentHashMap<User, IClient>();
timer = new Timer();
timer.schedule(new ClearDeadClients(), 5000, 5000);

...

class ClearDeadClients extends TimerTask {
public void run() {
synchronized (users) {
Iterator<User> it = users.iterator();
while (it.hasNext()) {
User user = it.next(); // Throws exception
if (!connectedUsers.contains(user)) {
users.remove(user);
clients.remove(user);
}
}
}

connectedUsers.clear();
}
}

最佳答案

您需要从迭代器而不是集合中移除。它看起来像这样:

Iterator<User> it = users.iterator();
while (it.hasNext()) {
User user = it.next();
if (!connectedUsers.contains(user)) {
it.remove();
clients.remove(user);
}
}

关于ArrayList 上的 java.util.ConcurrentModificationException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5145135/

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