Wiki Markup |
---|
According to the Java API documentation \[[API 2006|AA. Bibliography#API 06]\] for the {{Iterator.remove()}} method |
...
Such behavior may be observed in both single-threaded and multithreaded programs. Concurrent modification in single-threaded programs is usually a symptom of inserting or removing an element during iteration. Multithreaded programs add the possibility that a collection may be modified by one thread while another thread is iterating iterates over the collection. Unspecified behavior can result in either case. Many implementations throw a ConcurrentModificationException
when they detect concurrent modification.
...
This noncompliant code example (based on a SDN 2008 bug report 6687277) uses the Collection
's remove()
method to remove an element from an ArrayList
while iterating over the ArrayList
. The resulting behavior is unspecified.
...
The Iterator.remove()
method removes from the underlying Collection
the last element returned by the iterator. Its behavior is fully specified, so it may be safely invoked while iterating over a collection.
Code Block | ||
---|---|---|
| ||
// ... if(s.equals("one")) { iter.remove(); } // ... |
Noncompliant Code Example (Multithreaded)
This Although acceptable in a single-threaded environment, this noncompliant code example is insecure in a multithreaded environment because it is possible for another thread to modify the widgetList
while the current thread iterates over the widgetList
using the code shown below. Additionally, the doSomething()
method could also modify the collection during iteration.
...
Code Block | ||
---|---|---|
| ||
List<Widget> widgetList = new ArrayList<Widget>();
pubic void widgetOperation() {
List<Widget> deepCopy = new ArrayList<Widget>();
synchronized (widgetList) { // Client-side locking
for (Object obj : widgetList) {
deepCopy.add(obj.clone());
}
}
for (Widget w : deepCopy) {
doSomething(w);
}
}
|
...