Uploaded image for project: 'JDK'
  1. JDK
  2. JDK-8230377

Iterator created before List modification should throw Exception (CME)

    XMLWordPrintable

    Details

      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


        Attachments

          Issue Links

            Activity

              People

              Assignee:
              psonal Pallavi Sonal (Inactive)
              Reporter:
              webbuggrp Webbug Group
              Votes:
              0 Vote for this issue
              Watchers:
              1 Start watching this issue

                Dates

                Created:
                Updated:
                Resolved: