Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

ConcurrentModificationException not understanding why this is occurring all methods Are sync'd

 
joe vasher
Ranch Hand
Posts: 37
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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)
at java.util.ArrayList$Itr.next(ArrayList.java:791)
at com.pbuddie.Server.removeClient(Server.java:122)
at com.pbuddie.ClientConnect.run(ClientConnect.java:158)
 
P. Stefan Larsson
Greenhorn
Posts: 1
  • 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
joe vasher
Ranch Hand
Posts: 37
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks, huge help...
 
I agree. Here's the link: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic