Search code examples
javaloopsconcurrencyconcurrentmodification

Compile time check or java.util.ConcurrentModificationException


The loop below throws ConcurrentModificationException. Should it have given compiler error instead. What is the reason to go for Runtime Exception?

final List<String> list = new ArrayList<String>();
list.add("AAAAAAAAAAAAA");
for (final String it : list) {
    System.out.println(it);
    list.add("SSSSSSSSSS");
}

Solution

  • Some implementations of List may allow a call to add while being iterated via an Iterator. For example, CopyOnWriteArrayList would not throw a ConcurrentModificationException according to the javadoc.

    Why a RuntimeException? Because it is the programmer's job to know whether or not that specific implementation of List being used would allow that behavior. For what it is worth, there are static code analyzers like FindBugs which can warn you against dangerous patterns like that.