Search code examples
javamultithreadingmulticoreconcurrentmodification

Can a single core processor still throw ConcurrentModificationException?


If I spawn 2 threads on a single core PC does it ever access for example an ArrayList in the same time so it will throw ConcurrentModificationException?

My gut tells me although there are 2 threads, they cannot achieve true parallelism because there is a single core and what it can do mostly is to jump from one thread to another but without executing an instruction such as arrayList.add(element) in the same time.


Solution

  • TL;DR: Yes

        List<String> myList = new ArrayList<String>(Arrays.asList("My string"));
        Iterator<String> myIterator = myList.iterator();
        myList.add("Another string");
        myIterator.next();
    

    Result:

    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)
      at com.ajax.YourClass.yourMethod(YourClass.java:134)
    

    You shouldn’t modify the collection while iterating over it. In practice the ConcurrentModificationException usually comes (but is not guaranteed) when you call next() on an iterator after having added an element or removed one. And in practice it often happens when you add or remove an element from inside a loop iterating over the collection, as Carciganicate said in the comment.

    Or as ernest_k put it so well in the comment:

    "Concurrent" in ConcurrentModificationException is not really about parallelism