I'm like writing a process that keeps increasing itself (list) in a list loop in Java (at work)

I "Do you want to try it?"

List<String> list = new ArrayList<>(Arrays.asList("foo", "hoo", "hoge"));
for (String str : list) {
    list.add(str);
}
System.out.println(list);

//Exception occurred
// Exception in thread "main" java.util.ConcurrentModificationException
// 	at java.base/java.util.ArrayList$Itr.checkForComodification(ArrayList.java:1042)
// 	at java.base/java.util.ArrayList$Itr.next(ArrayList.java:996)

I "ConcurrentModificationException?" I "__ Who are you __" I "Do you want to try it with for Each?"

list.stream().forEach(list::add);
System.out.println(list);
// Exception in thread "main" java.util.ConcurrentModificationException
// 	at java.base/java.util.ArrayList$ArrayListSpliterator.forEachRemaining(ArrayList.java:1660)
//	at java.base/java.util.stream.ReferencePipeline$Head.forEach(ReferencePipeline.java:658)

I "No ..." I said, "If this is the case, I think I'll make the time after lunch, which is already sleepy, Siesta." I "Oh ..." Team leader "sig-kun" Team leader "I asked for an investigation in the morning, did you understand anything?" I "Leader ...!" I "(I haven't done it)" I "(For the time being __ I feel like I'm doing some work __ I showed you the current screen to get it)" I "like this" Team leader "How ..." Team leader "This exception called ConcurrentModificationException occurs when [__ when the number of elements in the original list is changed during iterative processing__]." Team leader "The Java iterator internally records the number of times __ has changed its own structure with the variable name modCount, and throws an exception if a discrepancy is found during repeated processing for that number of changes. It's becoming. "

Example: Implementation of ArrayList



//modCount with add(Number of changes)Is updated
public boolean add(E e) {
    modCount++;
    add(e, elementData, size);
    return true;
}

// modCount(Number of changes)Check of=>Throw an exception if there is a gap
final void checkForComodification() {
    if (modCount != expectedModCount)
        throw new ConcurrentModificationException();
}

//Check the number of changes each time you go to the next loop
public E next() {
    checkForComodification();  // modCount(Number of changes)Check is performed
    int i = cursor;
    if (i >= size)
        throw new NoSuchElementException();
    Object[] elementData = ArrayList.this.elementData;
    if (i >= elementData.length)
        throw new ConcurrentModificationException();
    cursor = i + 1;
    return (E) elementData[lastRet = i];
}

I "Oh" I "Why do you bother to do this?" Team Leader "Many Java collections use Failfast" I "Failfast?" Team leader "It's a cane that won't fall. Before it fails, it throws an exception when it senses a danger." Team leader "Java basically says it doesn't guarantee rewriting the structure of collections in multiple threads __" Team leader "This time it was single threaded, but I'm trying to throw an exception first so that it's okay if it's multithreaded." I "I see" I'm a cautious guy ... " Team leader "By the way, if you change the structure from outside the iterator, it's out, but you can follow it from inside the iterator __"

Add from inside the iterator


List<String> list = new ArrayList<>(Arrays.asList("foo", "hoo", "hoge"));
for (ListIterator<String> itr = list.listIterator(); itr.hasNext();) {
    String str = itr.next();
    itr.add(str + "_itr");
}
System.out.println(list);
// [foo, foo_itr, hoo, hoo_itr, hoge, hoge_itr]

I "Leader, __ I'm not in an infinite loop __" I "(I want to play while watching the array that keeps increasing infinitely until the fixed time ...)" Team leader "Because the element added by ListIterator.add is inserted just before __next of the iterator." Team leader "Does not affect subsequent hasNext () or next ()" I "(Seriously)" Team leader "I'd rather say it soon" Team leader "This __ has nothing to do with work " Team leader "Did you do the survey you asked for?" I " (not doing) " Team leader "I understand" Team leader "There are endless jobs, so for sig-kun, who seems to be free for the time being, this and that this week ..." I "leader!" Team leader "What" I " I'm leaving early because I sensed the danger " I " Failfast Return Home __" Team leader "Work because it's okay"

Rough Summary: What is ConcurrentModificationException?

Recommended Posts

I'm like writing a process that keeps increasing itself (list) in a list loop in Java (at work)
Create a named Skip List like redis sorted set in Java
I wrote a Stalin sort that feels like a mess in Java
Implement something like a stack in Java
Process every arbitrary number in Java List
A bat file that uses Java in windows
[Java] Execute a specific process in another thread with Executor Service [Avoid infinite loop]