Forums Register Login

About Vector and ConcurrentModificationException

+Pie Number of slices to send: Send
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 ?
+Pie Number of slices to send: Send
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
+Pie Number of slices to send: Send
 

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
+Pie Number of slices to send: Send
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.

+Pie Number of slices to send: Send
Thanks Steve and Henry .I got the concept
Being a smart alec beats the alternative. This tiny ad knows what I'm talking about:
a bit of art, as a gift, the permaculture playing cards
https://gardener-gift.com


reply
reply
This thread has been viewed 7838 times.
Similar Threads
ConcurrentModificationExc
Iterator are fail safe while Enumeration is not
Shared object used in all HTTP Requests: how to make it dynamic
Iterator can safely remove?
An Iterator throws a ConcurrentModificationException
More...

All times above are in ranch (not your local) time.
The current ranch time is
Apr 16, 2024 01:06:21.