Java Reference
In-Depth Information
Just as encapsulating an object's state makes it easier to preserve its invariants, encapsulating
its synchronization makes it easier to enforce its synchronization policy.
Listing 5.6. Iteration Hidden within String Concatenation.
Don't do this.
Iteration is also indirectly invoked by the collection's
hashCode
and
equals
methods,
which may be called if the collection is used as an element or key of another collection.
Similarly, the
containsAll
,
removeAll
, and
retainAll
methods, as well as the con-
structors that take collections are arguments, also iterate the collection. All of these indirect
uses of iteration can cause
ConcurrentModificationException
.
5.2. Concurrent Collections
Java 5.0 improves on the synchronized collections by providing several
concurrent
collection
classes. Synchronized collections achieve their thread safety by serializing all access to the
collection's state. The cost of this approach is poor concurrency; when multiple threads con-
tend for the collection-wide lock, throughput suffers.