Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java example code for generating a ConcurrentModificationException

I am expecting the code below to throw a ConcurrentModificationException, but instead I am getting an ArrayIndexOutOfBoundsException.

I am aware that a ConcurrentModificationException is not guaranteed as per javadoc included below, but I am attempting to recreate a scenario that leads to ConcurrentModificationException in order to better understand the mechanism of concurrency errors.

From ArrayList javadoc:

Fail-fast iterators throw ConcurrentModificationException on a best-effort basis. Therefore, it would be wrong to write a program that depended on this exception for its correctness: the fail-fast behavior of iterators should be used only to detect bugs.

public class RaceConditions {

    private static final int NUM_THREADS = 1000;
    private static final int NUM_ELEMENTS = 10000;
    private List<Integer> list = new ArrayList<>();

    public static void main(String... args) {

        for (int i = 0; i < NUM_THREADS; i++) {
            final int fi = i;

            new Thread() {
                @Override
                public void run() {
                    for (int j = 0; j < NUM_ELEMENTS; j++) {
                        list.add(0, fi);
                    }
                }
            }.start();
        }

        System.out.println(list.size());
    }
}

My question is what would I need to modify in the code above in order to get a guaranteed (or almost guaranteed) ConcurrentModificationException?

like image 416
ccpizza Avatar asked Jun 20 '26 10:06

ccpizza


1 Answers

This will give you always an ConcurrentModificationException

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

        list.add("Test");
        list.add("Test");
        list.add("Test");
        list.add("Test");
        list.add("Test");

        for(String item : list) {
            list.remove(item);
        }
    }
} 

This exception is thrown when ever you try to change a collection while you currently iterating over it.

like image 172
Marcinek Avatar answered Jun 22 '26 00:06

Marcinek