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

for each loop doesn't throw ConcurrentModificationException in special case

XMLWordPrintable

    • 8
    • generic
    • generic

      A DESCRIPTION OF THE PROBLEM :
      Following code snippet will not throw ConcurrentModificationException:
      public static void main(String[] args) {

      List<String> list = new ArrayList<>();

      list.add("a");
      list.add("b");
      list.add("c");
      list.add("d");
      list.add("e");
      list.add("f");
      list.add("g");

      for(String s: list){
      if(s.equals("f")){
      list.remove(s);
      }
      }

      list.stream().forEach(System.out::println);
      }

      This code will not throw exception because we are trying to remove the second last element from the list. It is replicated across multiple JVMs like 11,17,8 etc. I think, in this particular scenario, iterator doesn't call next method since the "g" will becomes the last element and iterator doesn't need to call next method.

      STEPS TO FOLLOW TO REPRODUCE THE PROBLEM :
      1. Create a list of elements in main methods
      2. use for(object obj: List) loop to loop through the list
      3. put the condition inside the loop to check if the current element is equal to the second last element, if Yes then remove it using list.remove method


      EXPECTED VERSUS ACTUAL BEHAVIOR :
      EXPECTED -
      It should throw the ConcurrentModificationException
      ACTUAL -
      It is not throwing the ConcurrentModificationException and program runs fine.

      ---------- BEGIN SOURCE ----------
      public static void main(String[] args) {

      List<String> list = new ArrayList<>();

      list.add("a");
      list.add("b");
      list.add("c");
      list.add("d");
      list.add("e");
      list.add("f");
      list.add("g");

      for(String s: list){
      if(s.equals("f")){
      list.remove(s);
      }
      }

      list.stream().forEach(System.out::println);
      }
      ---------- END SOURCE ----------

      FREQUENCY : always


            smarks Stuart Marks
            webbuggrp Webbug Group
            Votes:
            0 Vote for this issue
            Watchers:
            3 Start watching this issue

              Created:
              Updated: