• Post Reply Bookmark Topic Watch Topic
  • New Topic

About Vector and ConcurrentModificationException

 
RaviNada Kiran
Ranch Hand
Posts: 528
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi all, i have read this ,

when a thread iterates a vector while another thread changes the element of vector, either add or remove element a ConcurrentModificationException is thrown .
My question is that A Vector is a synchronized one ,how can this happen ?
 
steve souza
Ranch Hand
Posts: 862
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
There are probably times during the iteration when the vector is not synchronized. I am guessing between hasNext(), and next(). You could use a different collection that has synchronization that you want, or enclose/synchronize access to the collection. Also you should use List over the Vector
 
Henry Wong
author
Sheriff
Posts: 22537
109
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
There are probably times during the iteration when the vector is not synchronized. I am guessing between hasNext(), and next()....


It's more than just between the hasNext() and next() methods. The iterator was not designed to work with any change in the data structure. So, once an iterator is obtained, it must be used (to complete the operation) before any new data is added or old data is removed. The one exception is that elements can be deleted via the iterator.


Anyway, moving this topic to threads...

Henry
 
Steve Luke
Bartender
Posts: 4181
22
IntelliJ IDE Java Python
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This is actually documented in Vector's API. The solution is to synchronize the iteration of the Vector manually:


You will have to do the same thing for the List returned from the Collections.synchronizedList(...) method.

An alternative would be to use a safer and more modern List structure designed for concurrent operations, such as the java.util.concurrent.CopyOnWriteArrayList(). You should read CopyOnWriteArrayList's API to determine if it would be useful in your application (it may be much less efficient than simply synchronizing traversals).

Yet another option would be to take a snapshot of Vector and using that in your traversal operation. Taking a snapshot will require a traversal itself, and so should be synchronized, but if you spend time in the loop doing work it may make things more efficient but making the amount of time the Vector has to be synchronized shorter.

 
RaviNada Kiran
Ranch Hand
Posts: 528
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Steve and Henry .I got the concept
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!