...
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) {
// ...
}
}
}
|
...
This compliant solution synchronizes on the mapView
field rather than on the setView
field.
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 (mapView) { // Synchronize on map, rather than set
for (Integer k : setView) {
// ...
}
}
}
|
...
Rule | Severity | Likelihood | Remediation Cost | Priority | Level |
---|---|---|---|---|---|
LCK04-J | low | probable | medium | P4 | L3 |
Automated Detection
Some static analysis tools are capable of detecting violations of this rule.
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 |
...
Tasklist | ||||||||
---|---|---|---|---|---|---|---|---|
| ||||||||
||Completed||Priority||Locked||CreatedDate||CompletedDate||Assignee||Name||
|F|M|F|1270825291208| |dmohindr|suggested => "HashMap is not accessible, but the Map view is. Because the set view is synchronized instead of the map view, another thread can modify the contents of map and invalidate the k iterator."|
|