...
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 | ||
---|---|---|
| ||
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 | ||
---|---|---|
| ||
// ... iter.remove(); // ... |
Exceptions
EX1: The Iterator.remove()
method can be used to modify the underlying collection when an iteration is in progress. This is also shown in the compliant solution.
Risk Assessment
Modifying a Collection while iterating over it can lead to nondeterministic behavior.
Rule | Severity | Likelihood | Remediation Cost | Priority | Level |
---|---|---|---|---|---|
MSC38 MSC33- 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 |
...