JDK-8230377 : Iterator created before List modification should throw Exception (CME)
  • Type: Bug
  • Component: core-libs
  • Sub-Component: java.util:collections
  • Affected Version: 12.0.2
  • Priority: P4
  • Status: Closed
  • Resolution: Duplicate
  • OS: generic
  • CPU: generic
  • Submitted: 2019-08-29
  • Updated: 2021-01-27
  • Resolved: 2019-08-30
Related Reports
Duplicate :  
Description
A DESCRIPTION OF THE PROBLEM :
Iterators over non-concurrent collections like ArrayList, LinkedList, HashSet etc are "fail-fast". It means that any modifications to backend structure that are not done through iterator should result in ConcurrentModificationException (for iterator operation call). The implementations of ArrayList and LinkedList fails to throw this modification exception  (see method attached), when there are some items in the list -> list is modified with remove() operation  (so that it become empty) after an iterator is created -> and finally starting iteration over this.

STEPS TO FOLLOW TO REPRODUCE THE PROBLEM :
*>create a list object, either ArrayList or LinkedList.
*>add  items to list
*>create an iterator for iteration
*>do remove() operation such that list becomes empty
*>start iteration using iter.hasNext() and iter.next() calls.


EXPECTED VERSUS ACTUAL BEHAVIOR :
EXPECTED -
should have thrown exception since list has been structurally modified.
ACTUAL -
No exception is thrown.

---------- BEGIN SOURCE ----------
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;


public class ListBug {
    
    public static void main(String[] args) {
        // 1. create a list
        List<Integer> list = new ArrayList<>();
        
        // 2. add some items to it
        for (int i = 0; i < 5; i++) {
            list.add(i);
        }
        
        // 3. create an iterator to iterate over
        Iterator<Integer> iter = list.iterator();
       
        // 4. remove all items from the list
        for (int i = 0; i < 5; i++) {
            list.remove(0);
        }
        
        // 5. continue with the iteration
        while (iter.hasNext()) {
            System.out.println(iter.next());
        }
    }
    
}
---------- END SOURCE ----------

CUSTOMER SUBMITTED WORKAROUND :
None.

FREQUENCY : always