Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Wiki Markup
The {{java.util.Collections}} interface's documentation \[[API 2006|AA. Bibliography#API 06]\] warns about the consequences of failing to synchronize on an accessible collection object when iterating over its view:
{quote}
It is imperative that the user manually synchronize on the returned map when iterating over any of its collection views...  Failure to follow this advice may result in non-deterministic behavior.
{quote}

Any class that uses a collection view as the lock object rather than using 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 also have accessible backing collections must synchronize on the backing collection; synchronization on the view is prohibited.

{mc} I don't see the point of this statement 
To make a group of statements atomic, synchronize on the original collection object when using synchronization wrappers.([CON07-J. Do not assume that a group of calls to independently atomic methods is atomic]). 
{mc}


h2. Noncompliant Code Example (Collection View)

This noncompliant code example creates a {{HashMap}} object, and two viewsview objects: a synchronized view of an empty {{HashMap}} encapsulated by the {{map}} field and a set view of the map's keys encapsulated by the {{set}} field. This example synchronizes on the {{set}} view \[[Tutorials 2008|AA. Bibliography#Tutorials 08]\].

{code:bgColor=#FFcccc}
private final Map<Integer, String> map = Collections.synchronizedMap(new HashMap<Integer, String>());
private final Set<Integer> set = map.keySet();

public Map<Integer, String> getMap() {
  return map;
}

public void doSomething() {
  synchronized (set) {  // Incorrectly synchronizes on set
    for (Integer k : set) {
      // ...
    }
  }
}
{code}

In this example, {{HashMap}} provides the backing collection for {{Map}}the synchronized map, which provides the backing collection for {{Set}}, as shown in the following figure:

!con06-j-backing-collection.JPG!

The {{HashMap}} object is inaccessibleinaccessable, but the synchronized view referenced by the {{map}} viewfield is accessible via the {{getMap()}} method.  Because the {{setsynchronized}} view is statement uses the intrinsic lock of the synchronized butset the {{map}} view is unsynchronizedand not the synchronized map, another thread can modify the contents ofsynchronized {{map}}, and invalidate the {{k}} iterator.


h2. Compliant Solution (Collection Lock Object)

This compliant solution synchronizes on the {{map}} viewfield rather than on the {{set}} viewfield. 

{code:bgColor=#ccccff}
private final Map<Integer, String> map = Collections.synchronizedMap(new HashMap<Integer, String>());
private final Set<Integer> set = map.keySet();

public Map<Integer, String> getMap() {
  return map;
}

public void doSomething() {
  synchronized (map) {  // Synchronize on map, not set
    for (Integer k : set) {
      // ...
    }
  }
}
{code}

This code is compliant because the map's underlying structure cannot be changed while an iteration is in progress.

h2. Risk Assessment

Synchronizing on a collection view instead of the collection object can cause nondeterministic behavior.

|| Rule || Severity || Likelihood || Remediation Cost || Priority || Level ||
| LCK04-J  | low | probable | medium | {color:green}{*}P4{*}{color} | {color:green}{*}L3{*}{color} |


h3. Related Vulnerabilities 

Any vulnerabilities resulting from the violation of this rule are listed on the [CERT website|https://www.kb.cert.org/vulnotes/bymetric?searchview&query=FIELD+KEYWORDS+contains+CON36-J].


h2. Bibliography

| \[[API 2006|AA. Bibliography#API 06]\] | Class Collections |
| \[[Tutorials 2008|AA. Bibliography#Tutorials 08]\] | [Wrapper Implementations|http://java.sun.com/docs/books/tutorial/collections/implementations/wrapper.html] |


h2. Issue Tracking 

{tasklist:Review List} 
||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."| 
{tasklist}

----
[!The CERT Oracle Secure Coding Standard for Java^button_arrow_left.png!|LCK03-J. Do not synchronize on the intrinsic locks of high-level concurrency objects]&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;[!The CERT Oracle Secure Coding Standard for Java^button_arrow_up.png!|08. Locking (LCK)]&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;[!The CERT Oracle Secure Coding Standard for Java^button_arrow_right.png!|LCK05-J. Synchronize access to static fields that can be modified by untrusted code]