Home  >  Article  >  Java  >  How Can I Avoid Concurrent Modification Exceptions When Iterating and Modifying Java Lists?

How Can I Avoid Concurrent Modification Exceptions When Iterating and Modifying Java Lists?

Susan Sarandon
Susan SarandonOriginal
2024-11-21 09:43:10374browse

How Can I Avoid Concurrent Modification Exceptions When Iterating and Modifying Java Lists?

Concurrent Modification Exception in Java

The "Concurrent Modification" exception occurs when multiple threads attempt to modify a shared data structure, such as a list, simultaneously. This can lead to unexpected results and data corruption.

Consider the following Java code:

import java.util.*;

public class SomeClass {
    public static void main(String[] args) {
        List<String> s = new ArrayList<>();
        ListIterator<String> it = s.listIterator();

        for (String a : args)
            s.add(a);

        if (it.hasNext())
            String item = it.next();

        System.out.println(s);
    }
}

This code attempts to iterate over a list while simultaneously modifying it. When it runs, the "Concurrent Modification Exception" is thrown. This is because the list iterator was created before any changes were made to the list.

To avoid this exception, you should ensure that only one thread can modify the list at a time. You can do this by creating the iterator only after all modifications to the list have been made. The correct code is:

import java.util.*;

public class SomeClass {

    public static void main(String[] args) {
        List<String> s = new ArrayList<>();

        for(String a : args)
            s.add(a);

        ListIterator<String> it = s.listIterator();    
        if(it.hasNext()) {  
            String item = it.next();   
        }  

        System.out.println(s);

    }
}

By creating the iterator after the list has been modified, you ensure that only a single thread has access to the list during the iteration. This prevents the "Concurrent Modification Exception" from occurring.

The above is the detailed content of How Can I Avoid Concurrent Modification Exceptions When Iterating and Modifying Java Lists?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn