Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: Migration of unmigrated content due to installation of a new plugin

The Java Tutorials, Wrapper Implementations [Java Tutorials], warns about the consequences of failing to synchronize on an accessible collection object when iterating over its view:

It is imperative that the user manually synchronize on the returned Map when iterating over any of its Collection views rather than synchronizing on the Collection view itself.

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

Code Block
bgColor#FFcccc
private final Map<Integer, String> mapView =
   
Wiki Markup
The {{java.util.Collections}} interface's documentation \[[API 06|AA. Java References#API 06]\] warns about the consequences of synchronizing on any view over a collection object, rather than synchronizing on the collection object itself.
{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}

Synchronize on the original Collection object when using synchronization wrappers to enforce atomicity ([CON07-J. Do not assume that a group of calls to independently atomic methods is atomic]).

{mc} This also applies to {{java.util.Map}} objects, even though Maps are technically not Collections. -- Good point but I think you mean the Collections interface. Acc to interface map API: "This interface is a member of the Java Collections Framework". Moreover it has collection views as stated in the API ref.  -- No, I mean the Collection interface. Collections is a class with several static methods.  Maps are part of the Collection framework even though they don't implement {{Collection}}. Hence I removed bracees ~DS {mc}

h2. Noncompliant Code Example (collection view)

This noncompliant code example incorrectly synchronizes on the {{set}} view of the synchronized map ({{map}}) instead of the collection object \[[Tutorials 08|AA. Java References#Tutorials 08]\].

{code:bgColor=#FFcccc}
// map has package-private accessibility
final Map<Integer, String> map = Collections.synchronizedMap(new HashMap<Integer, String>());
private final Set<Integer> setsetView = mapmapView.keySet();

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

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

h2. Compliant Solution (collection lock object)

This compliant solution synchronizes on the original {{Collection}} object {{map}} instead of the {{Collection}} view {{set}}. 

{code:bgColor=#ccccff}
// map has package-private accessibility

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.

Image Added

The 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 k iterator.

Compliant Solution (Collection Lock Object)

This compliant solution synchronizes on the mapView field rather than on the setView field:

Code Block
bgColor#ccccff
private final Map<Integer, String> mapmapView =
    Collections.synchronizedMap(new HashMap<Integer, String>());
private final Set<Integer> setsetView = mapmapView.keySet();

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

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

h2. Risk Assessment

Synchronizing on a collection view instead of the collection object may cause non-deterministic behavior. 

|| Rule || Severity || Likelihood || Remediation Cost || Priority || Level ||
| CON40-J | medium | probable | medium | {color:#cc9900}{*}P8{*}{color} | {color:#cc9900}{*}L2{*}{color} |


h3. Related Vulnerabilities

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

h2. References

\[[API 06|AA. Java References#API 06]\] Class Collections
\[[Tutorials 08|AA. Java References#Tutorials 08]\] [Wrapper Implementations|http://java.sun.com/docs/books/tutorial/collections/

This code is compliant because the map's underlying structure cannot be changed during the iteration.

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

P4

L3

Automated Detection

Some static analysis tools are capable of detecting violations of this rule.

ToolVersionCheckerDescription
Parasoft Jtest

Include Page
Parasoft_V
Parasoft_V

CERT.LCK04.SOBCDo not synchronize on a collection view if the backing collection is accessible
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

Issue Tracking

Tasklist
Review List
Review List
sortAscendingfalse
sortBypriority
implementations/wrapper.html]

h2. Issue Tracking

{tasklist:Review List}
||Completed||Priority||Locked||CreatedDate||CompletedDate||Assignee||Name||
|F|M|F|12694530746511270825291208|          |dmohindr|"warnssuggested about=> the"HashMap consequencesis of synchronizing on any view over a collection object, rather than synchronizing on the collection object" ... it doesn't warn against it...it just says you should synchronize the collection...suggest reverting the change|
|F|M|F|1269452979738|          |dmohindr|The title could do away with "still"|
{tasklist}


----
[!The CERT Sun Microsystems Secure Coding Standard for Java^button_arrow_left.png!|VOID CON00-J. Synchronize access to shared mutable variables]&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;[!The CERT Sun Microsystems Secure Coding Standard for Java^button_arrow_up.png!|11. Concurrency (CON)]&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;[!The CERT Sun Microsystems Secure Coding Standard for Java^button_arrow_right.png!|CON03-J. Do not use background threads during class initialization]
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."|


...

Image Added Image Added Image Added