Java Reference
In-Depth Information
5.1.2. Iterators and Concurrentmodificationexception
We use Vector for the sake of clarity in many of our examples, even though it is considered
a “legacy” collection class. But the more “modern” collection classes do not eliminate the
problem of compound actions. The standard way to iterate a Collection is with an
Iterator , either explicitly or through the for-each loop syntax introduced in Java 5.0, but
using iterators does not obviate the need to lock the collection during iteration if other threads
can concurrently modify it. The iterators returned by the synchronized collections are not
designed to deal with concurrent modification, and they are fail-fast —meaning that if they
detect that the collection has changed since iteration began, they throw the unchecked Con-
currentModificationException .
These fail-fast iterators are not designed to be foolproof—they are designed to catch con-
currency errors on a “good-faith-effort” basis and thus act only as early-warning indicators
for concurrency problems. They are implemented by associating a modification count with
the collection: if the modification count changes during iteration, hasNext or next throws
ConcurrentModificationException . However, this check is done without syn-
chronization, so there is a risk of seeing a stale value of the modification count and therefore
that the iterator does not realize a modification has been made. This was a deliberate design
tradeoff to reduce the performance impact of the concurrent modification detection code. [2]
Listing 5.5 illustrates iterating a collection with the for-each loop syntax. Internally, javac
generates code that uses an Iterator , repeatedly calling hasNext and next to iterate
the List . Just as with iterating the Vector , the way to prevent ConcurrentModific-
ationException is to hold the collection lock for the duration of the iteration.
Listing 5.5. Iterating a List with an Iterator .
There are several reasons, however, why locking a collection during iteration may be undesir-
able. Other threads that need to access the collection will block until the iteration is complete;
if the collection is large or the task performed for each element is lengthy, they could wait a
Search WWH ::




Custom Search