It is imperative that the user manually synchronize on the returned
Mapwhen iterating over any of its
Collectionviews rather than synchronizing on the
Disregarding this advice may result in nondeterministic behavior.
Any class that uses a collection view rather than the backing collection as the lock object may end up with two distinct locking strategies. When the backing collection is accessible to multiple threads, the class that locked on the collection view has violated the thread-safety properties and is unsafe. Consequently, programs that both require synchronization while iterating over collection views and have accessible backing collections must synchronize on the backing collection; synchronization on the view is a violation of this rule.
Noncompliant Code Example (Collection View)
This noncompliant code example creates a
HashMap object and two view objects: a synchronized view of an empty
HashMap encapsulated by the
mapView field and a set view of the map's keys encapsulated by the
setView field. This example synchronizes on
setView [Java Tutorials].
In this example,
HashMap provides the backing collection for the synchronized map represented by
mapView, which provides the backing collection for
setView, as shown in the following figure.
HashMap object is inaccessible, but
mapView is accessible via the public
getMap() method. Because the
synchronized statement uses the intrinsic lock of
setView rather than of
mapView, another thread can modify the synchronized map and invalidate the
Compliant Solution (Collection Lock Object)
This compliant solution synchronizes on the
mapView field rather than on the
This code is compliant because the map's underlying structure cannot be changed during the iteration.
Synchronizing on a collection view instead of the collection object can cause nondeterministic behavior.
Some static analysis tools are capable of detecting violations of this rule.
|Do not synchronize on a collection view if the backing collection is accessible