Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

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
bgColor#FFcccc

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
bgColor#ccccff

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.

ToolVersionCheckerDescription
ThreadSafe
Include Page
ThreadSafe_V
ThreadSafe_V

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

...

Tasklist
Review List
Review List
sortAscendingfalse
sortBypriority

||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."|

 

      08. Locking (LCK)