The java.util.Collections
interface's documentation [API 2006] warns about the consequences of failing to synchronize on an accessible collection object when iterating over its 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
[Tutorials 2008].
Code Block | ||
---|---|---|
| ||
private final Map<Integer, String> mapView = Collections.synchronizedMap(new HashMap<Integer, String>()); private final Set<Integer> setView = mapView.keySet(); public Map<Integer, String> getMap() { return mapView; } public void doSomething() { synchronized (setView) { // Incorrectly synchronizes on setView for (Integer k : setView) { // ... } } } |
...
Tool | Version | Checker | Description | ||||||
---|---|---|---|---|---|---|---|---|---|
ThreadSafe |
| CCE_CC_SYNC_ON_VIEW CCE_CC_ITER_VIEW_NO_LOCK CCE_CC_ITER_VIEW_BOTH_LOCKS CCE_CC_ITER_VIEW_WRONG_LOCK | Implemented |
Bibliography
[API 2006] | Class Collections |
Issue Tracking
...