Versions Compared

Key

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

...

The message is clear, do not rely on ConcurrentModificationException to stop any side effects resulting from modifying an underlying Collection while iterating over it. Notably, the enhanced for loop (for-each) internally uses an Iterator.

Noncompliant Code Example

This noncompliant code example (based on a bug report 6687277) removes an element from an ArrayList using the Collection's remove() method. This is done while iterating over the Collection. The resulting behavior is unspecified.

Code Block
bgColor#FFcccc
class BadIterate {
  public static void main(String[] args) {
  List<String> list = new ArrayList<String>();
  list.add("one");
  list.add("two");
        
  Iterator iter = list.iterator();
  while(iter.hasNext()) {
    String s = (String)iter.next();
    if(s.equals("one"))
      list.remove(s);
    }
  }    
}

Compliant Solution

The Iterator.remove() method removes from the underlying Collection, the last element returned by the iterator. Its behavior is fully specified.

Code Block
bgColor#ccccff
// ...
iter.remove();
// ...

Risk Assessment

Modifying a Collection while iterating over it can lead to nondeterministic behavior unless the Iterator.remove() method is used.

Rule

Severity

Likelihood

Remediation Cost

Priority

Level

MSC39-J

low

probable

medium

P4

L3

Automated Detection

TODO

Related Vulnerabilities

Search for vulnerabilities resulting from the violation of this rule on the CERT website.

References

Wiki Markup
\[[API 06|AA. Java References#API 06]\] Class [ConcurrentModificationException|http://java.sun.com/j2se/1.5.0/docs/api/java/util/ConcurrentModificationException.html] 
\[[SDN 08|AA. Java References#SDN 08]\] [Sun Bug database, Bug ID:6687277|http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6687277]
\[[Goetz 06|AA. Java References#Goetz 06]\] 5.1.2. Iterators and Concurrentmodificationexception

...

MSC37-J. Make sensitive classes noncloneable      MSC39MSC38-J. Do not modify the underlying collection when an iteration is in progress      [|# 49. Miscellaneous (MSC)
]