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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With