Java Reference
In-Depth Information
Because it has so many advantages and so few disadvantages compared to
Hashtable
or
synchronizedMap
, replacing synchronized
Map
implementations with
Concur-
rentHashMap
in most cases results only in better scalability. Only if your application needs
in replacement.
5.2.2. Additional Atomic Map Operations
Since a
ConcurrentHashMap
cannot be locked for exclusive access, we cannot use
client-side locking to create new atomic operations such as put-if-absent, as we did for
Vector
in
Section 4.4.1
.
Instead, a number of common compound operations such as put-if-
absent, remove-if-equal, and replace-if-equal are implemented as atomic operations and spe-
such functionality to an existing synchronized
Map
implementation, it is probably a sign that
you should consider using a
ConcurrentMap
instead.
5.2.3. CopyOnWriteArrayList
CopyOnWriteArrayList
is a concurrent replacement for a synchronized
List
that of-
fers better concurrency in some common situations and eliminates the need to lock or copy
the collection during iteration. (Similarly,
CopyOnWriteArraySet
is a concurrent re-
placement for a synchronized
Set
.)
The copy-on-write collections derive their thread safety from the fact that as long as an ef-
fectively immutable object is properly published, no further synchronization is required when
accessing it. They implement mutability by creating and republishing a new copy of the col-
lection every time it is modified. Iterators for the copy-on-write collections retain a reference
to the backing array that was current at the start of iteration, and since this will never change,
they need to synchronize only briefly to ensure visibility of the array contents. As a res-
ult, multiple threads can iterate the collection without interference from one another or from
threads wanting to modify the collection. The iterators returned by the copy-on-write col-
lections do not throw
ConcurrentModificationException
and return the elements
exactly as they were at the time the iterator was created, regardless of subsequent modifica-
tions.
Listing 5.7.
ConcurrentMap
Interface.