JDK-8265904 : ArrayList remove() method implementation issue
  • Type: Bug
  • Component: core-libs
  • Sub-Component: java.util:collections
  • Affected Version: 8,11,17
  • Priority: P4
  • Status: Closed
  • Resolution: Duplicate
  • Submitted: 2021-04-23
  • Updated: 2021-05-25
  • Resolved: 2021-05-12
Related Reports
Duplicate :  
Description
A DESCRIPTION OF THE PROBLEM :
When we are trying to call remove(Object o) method of ArrayList, while iterating then it throws ConcurrentModificationException always for any element that we are trying to remove from arraylist. But not for the second last element of the arraylist. 
For the second last element, remove(Object o) method of ArrayList class is working perfectly fine which I believe is a bug and should be reported. 

STEPS TO FOLLOW TO REPRODUCE THE PROBLEM :
1. Create one ArrayList object of String type.
2. Add four names of your choice.
3. Iterate list using for each loop.
4. Now, make one condition in such a way that only when you are fetching second last element from list, call remove(Object O) method of Arraylist and pass the element as an argument to the method.
5. You will see, any exception will not be thrown.
6. Whereas, if you call the same method for any element on any index except the second last, it will throw ConcurrentModificationException

EXPECTED VERSUS ACTUAL BEHAVIOR :
EXPECTED -
For every element which is being removed or modified while iterating the ArrayList object should not be removed and should throw ConcurrentModificationException always
ACTUAL -
1. You will see, any exception will not be thrown.
2. Whereas, if you call the same method for any element on any index except the second last, it will throw ConcurrentModificationException

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

public class FailFastOrFailSafe {

	public static void main(String[] args) {
		
		ArrayList<String> al = new ArrayList<String>();
		al.add("Jack");
		al.add("John");
		al.add("Mac");
		al.add("Karlos");
		

		

		for(String s : al)
		{
			
			if(s.equals("Mac"))
			{
				al.remove(s);
			
			}
			
			
		}
		
	System.out.println(al);
	}
}

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

FREQUENCY : always



Comments
Sounds familiar. Stuart will probably close it as a known duplicate.
26-04-2021

The observations on Windows 10: JDK 8: Failed, no exception thrown. JDK 11: Failed. JDK 17ea+6: Failed.
25-04-2021