java.util.ConcurrentModificationException上的ArrayList [英] java.util.ConcurrentModificationException on ArrayList

查看:154
本文介绍了java.util.ConcurrentModificationException上的ArrayList的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个服务器类和里面一个定时器这是应该清除死的客户端(客户谁崩溃)。我跟着下面的例子中通过锁定集合时,定时器遍历用户,但我仍然得到此异常(后我崩溃连接的客户端)。

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

 列表<使用者>用户;
清单<使用者> connectedUsers;
ConcurrentMap<使用者,IClient>客户;...用户= Collections.synchronizedList(新的ArrayList<使用者>());
connectedUsers =新的ArrayList<使用者>();
客户=新的ConcurrentHashMap<使用者,IClient>();
定时器=新定时器();
timer.schedule(新ClearDeadClients(),5000,5000);...类ClearDeadClients扩展的TimerTask {
    公共无效的run(){
        同步的(用户){
            迭代器<使用者>它= users.iterator();
            而(it.hasNext()){
                用户的用户= it.next(); //抛出异常
                如果(!connectedUsers.contains(用户)){
                    users.remove(用户);
                    clients.remove(用户);
                }
            }
        }        connectedUsers.clear();
    }
}


解决方案

您需要从迭代器而不是集合中删除。它是这样的,而不是:

 的Iterator<使用者>它= users.iterator();
而(it.hasNext()){
    用户的用户= it.next();
    如果(!connectedUsers.contains(用户)){
         it.remove();
         clients.remove(用户);
     }
}

I have a Server class and a Timer inside it which is supposed to clear dead clients (clients who crashed). I followed the example below by locking the collection when the Timer iterates over the users but I still get this exception (after I crash a connected client).

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

解决方案

You need to remove from the iterator not the collection. It would look like this instead:

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

这篇关于java.util.ConcurrentModificationException上的ArrayList的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆