JDK-8182026 : Remove method is not throwing java.util.ConcurrentModificationException in List
  • Type: Bug
  • Component: core-libs
  • Sub-Component: java.util:collections
  • Affected Version: 8
  • Priority: P4
  • Status: Closed
  • Resolution: Duplicate
  • OS: windows_7
  • CPU: x86_64
  • Submitted: 2017-06-08
  • Updated: 2017-06-13
  • Resolved: 2017-06-13
Related Reports
Duplicate :  
Description
FULL PRODUCT VERSION :
jdk 8

ADDITIONAL OS VERSION INFORMATION :
all version

A DESCRIPTION OF THE PROBLEM :
package org.vc.testing;

import java.util.ArrayList;
import java.util.List;

public class TestList {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		List<String> l = new ArrayList<String>();
		  
		l.add("Mr.");
		l.add("Vikas");
	//	l.add("Choudhary");
		for(String ll : l){
			l.remove(ll);
			System.out.println(ll);
		}
	}

}


STEPS TO FOLLOW TO REPRODUCE THE PROBLEM :
We are traversing over list and making modification. In case we are not using Iterator interface then program will throw java.util.ConcurrentModificationException . but If list contains only two elements, execution is fine without Iterator.

EXPECTED VERSUS ACTUAL BEHAVIOR :
EXPECTED -
If we are not using Iterator interface and making modification then It should throw java.util.ConcurrentModificationException . 

REPRODUCIBILITY :
This bug can be reproduced always.

---------- BEGIN SOURCE ----------
package org.vc.testing;

import java.util.ArrayList;
import java.util.List;

public class TestList {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		List<String> l = new ArrayList<String>();
		  
		l.add("Mr.");
		l.add("Vikas");
		//l.add("Choudhary");
		for(String ll : l){
			l.remove(ll);
			System.out.println(ll);
		}
	}

}

---------- END SOURCE ----------

CUSTOMER SUBMITTED WORKAROUND :
For each operation on list you are increment modCount. In case we are not using Iterator interface then based on modCount and expectedmodCount, we should throw exception first time only. because code comparing these two count after removing.

We should make changes in remove(Object a) method accordingly. 


Comments
This is a duplicate of JDK-8136821. " Modifying a collection while it's being iterated is considered to be a programming error. The detection of this situation and the consequent throwing of ConcurrentModificationException is performed on a "best-effort" basis. It's improper for a program to rely on CME to be thrown in particular cirumstances. This is described in the class specification of ArrayList, and similar wording appears in the specification of other core collections, such as HashMap. The prevailing style of the core collections is to check for concurrent modification only during an Iterator's next() call but not within its hasNext() call. ArrayList conforms to this style. "
13-06-2017