Professional Documents
Culture Documents
What is a mysterious field called modCount doing in the List Iterator classes? How can we
efficiently handle iterating over collections when another thread may be updating the
collection at the same time?
AbstractList
Iterators
Iterator iterator();
ListIterator listIterator();
ListIterator listIterator(int index);
Concurrency Problems
Corruption
Just as databases lock tables and rows while performing updates, we could
lock the collection while we were iterating over it to solve the concurrent
access/update problem. In this scenario, we prevent any thread from
changing the collection while iteration takes place, thus guaranteeing
predictable behavior. So, we might use a Vector object for our collection
since that class has its accessors and updators synchronized on the Vector
object itself. Then your iteration can lock the Vector simply:
Copy On Write
Fast Fail
This scenario has a very small overhead in the additional cost of updating
the modCount variable on any change to the collection, and comparing the
modCount variable for each iteration. This should be negligible in most
cases.