ConcurrentModificationException

hey guys,,

I have been working on a server and after doing some testing I found out that it gives me ConcurrentModificationException when many users are joining at the same time.

my error comes from for(User us: room.getUsers) in this method:

private void addToRoom(User user, Room room){

for(User us: room.getUsers()){

send(us, Events.onUserEnteredRoom, userToString(user));

}

user.setRoom(room);

room.addUser(user);

}

room.getUsers() returns a set. The problems seems to be that later line room.addUser(user); is modifying the set while i am iterating if i have too many clients join at the same time. But if i synchronized users in my addUsers method why would that be a problem? :

public void addUser(User u)

{

synchronized(users){

users.add(u);

}

}

I would appreciate if someone could tell me why i am getting the error still.

[942 byte] By [fanar77450a] at [2007-11-26 16:46:03]
# 1
You need to synchronize on the set while you are iterating over it as well as when adding to it or removing from it.
ejpa at 2007-7-8 23:13:26 > top of Java-index,Core,Core APIs...
# 2
well if its synchronized in the add and remove, doesnt it mean that the iterator cant iterate through till its done adding and removing?
fanar77450a at 2007-7-8 23:13:26 > top of Java-index,Core,Core APIs...
# 3
Obviously not, or you wouldn't be having this problem, would you?
ejpa at 2007-7-8 23:13:26 > top of Java-index,Core,Core APIs...
# 4

> Obviously not, or you wouldn't be having this

> problem, would you?

Hi would if iterating is not sycronous. Nothing prevent from starting iteration and then add something or remove.

See collections for thread proff incarnation.

http://java.sun.com/j2se/1.5.0/docs/api/java/util/Collections.html#synchronizedCollection(java.util.Collection)

_Dima_a at 2007-7-8 23:13:26 > top of Java-index,Core,Core APIs...
# 5
> He would if iterating is not sychronous.How is that different from what I've been saying?
ejpa at 2007-7-8 23:13:26 > top of Java-index,Core,Core APIs...
# 6
It is not anti-statement. I beg Your pardon if it was not clear. I was just to highlight Your phrase and put some more details.
_Dima_a at 2007-7-8 23:13:26 > top of Java-index,Core,Core APIs...
# 7
> > He would if iterating is not sychronous.> > How is that different from what I've been saying?because it wasn't you saying it, presumably. you know how some people like to be heard.....
georgemca at 2007-7-8 23:13:26 > top of Java-index,Core,Core APIs...
# 8
and 'highlight' phrases that don't need any more highlighting, and 'put in more details' that were already there in the question, and obfuscate a discussion that was perfectly clear ...
ejpa at 2007-7-8 23:13:26 > top of Java-index,Core,Core APIs...