[Java] Explains ConcurrentModificationException that occurs in java.util.ArrayList for newcomers

Introduction

ConcurrentModificationException that also occurs in a single thread

DenaiConcurrentModificationException.java


public static void main(String[] args) {
	List<String> list = new ArrayList<String>();
	
	list.add("A");
	list.add("B");
	list.add("C");
	list.add("D");
	
	for (String str : list) {
		if ("C".equals(str)) {
			list.remove(str);
		} else {
			System.out.println(str);
		}
	}
}

DeruConcurrentModificationException.java


public static void main(String[] args) {
	List<String> list = new ArrayList<String>();
	
	list.add("A");
	list.add("B");
	list.add("C");
	list.add("D");
	list.add("E");
	
	for (String str : list) {
		if ("C".equals(str)) {
			list.remove(str);
		} else {
			System.out.println(str);
		}
	}
}

When does a ConcurrentModificationException occur?

Java 8 SE ConcurrentModificationException documentation

This exception is thrown when a method that detects a parallel change in an object does not allow such a change.
For example, it is generally not allowed for one thread to iterate over a collection while another thread modifies the collection.
In such an environment, the results of iterative processing are usually not guaranteed.
Some iterators(Iterator)Implementation of(JREが提供するすべての一般的な目的のコレクションImplementation ofの、イテレータImplementation ofを含む)Is
You can choose to throw this exception if that behavior is detected.
The iterator that throws this exception is called a failfast iterator.
Iterators throw exceptions immediately and neatly to avoid the risk of unpredictable behavior at unpredictable points in the future.
This exception does not necessarily indicate that the object has not been updated in parallel by another thread.
If a single thread issues a set of methods that violate the object's conventions, the object throws this exception.
For example, if a thread modifies a collection directly while iterating over a collection with a failfast iterator.
The iterator throws this exception.

Take a look at the implementation of java.util.ArrayList

java


/**
 * An optimized version of AbstractList.Itr
 */
private class Itr implements Iterator<E> {}

With *, ConcurrentModificationException is thrown if there is a difference between expectedModCount and modCount every time the cursor moves. You can guess the role of the property from the name.

java


final void checkForComodification() {
    if (modCount != expectedModCount)
        throw new ConcurrentModificationException();
}

java


/*
 * Private remove method that skips bounds checking and does not
 * return the value removed.
 */
private void fastRemove(int index) {
    modCount++;
    int numMoved = size - index - 1;
    if (numMoved > 0)
        System.arraycopy(elementData, index+1, elementData, index,
                         numMoved);
    elementData[--size] = null; // clear to let GC do its work
}

skitch.3.png skitch.4.png

Summary

Recommended Posts

[Java] Explains ConcurrentModificationException that occurs in java.util.ArrayList for newcomers
This and that for editing ini in Java. : inieditor-java
[SQLite] IllegalStateException that occurs in Cursor
Java version notation that changes in Java 10
Rock-paper-scissors game for beginners in Java
[For beginners] Run Selenium in Java
Settings for SSL debugging in Java
About the phenomenon that StackOverflowError occurs in processing using Java regular expressions
First steps for deep learning in Java
Key points for introducing gRPC in Java
[Java] for Each and sorted in Lambda
ERRORCODE = -4471 occurs in Java application using Db2.
[Java] Why no compilation error occurs for classes that do not implement Comparable
Java that outputs vmg format file in eml format
ChatWork4j for using the ChatWork API in Java
Technology for reading Java source code in Eclipse
Solution for NetBeans 8.2 not working in Java 9 environment
A bat file that uses Java in windows
Set pop-up display for Java language in vim.
General-purpose StringConverter class that utilizes generics in Java8
Compare PDF output in Java for snapshot testing
Enable / disable SNI in Java for each communication
Things to watch out for in Java equals