ConcurrentModificationException not understanding why this is occurring all methods Are sync'd
Joined: Nov 06, 2009
I wrote a server class that works with a List<ClientInfo> clientMap = new ArrayList<ClientInfo>();
all methods that modify or read this list are in the server object and synchronized. Access to these methods are coming from different threads.. (my thought is only 1 of these methods can be used at a time...) so How the heck can i be getting a ConcurrentModificationException?
Thanks in advance.
After reading the exception I thought I might include the method at fault: + the only other two methods that could have occurred during this exception.
Exception in thread "test" java.util.ConcurrentModificationException at java.util.ArrayList$Itr.checkForComodification(ArrayList.java:819)
P. Stefan Larsson
Joined: Aug 30, 2011
When you use an iterator, you're supposed to use the iterator to remove items, not the underlying collection, even if everything is in a single thread. Try it.remove() instead?
According to the ConcurrentModificationException javadoc: "if a thread modifies a collection directly while it is iterating over the collection with a fail-fast iterator, the iterator will throw this exception"
By the way, perhaps you should use a Map (e.g. HashMap or maybe ConcurrentHashMap) instead of a List for quicker removal? Use the id of the ClientInfo as a key.
Another thing, be careful with calling methods from synchronized methods, if you synchronize every complete method in every class you're likely to hold multiple locks at once, in different order in different threads, causing a deadlock. It's better to use small synchronized blocks and only when you have to.