2

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.

ernest_k
  • 44,416
  • 5
  • 53
  • 99
ZeNstok
  • 130
  • 1
  • 7
  • 5
    "Concurrent" in `ConcurrentModificationException` is not really about parallelism (even if concurrent access to data makes the typical scenario for it). The conditions for the exception are created when a collection is modified after iteration has started and before it ends (and all can happen in a single thread). To make it specific to iteration, maybe we could better call it `ModificationDuringIterationException`. – ernest_k Nov 01 '20 at 18:39

2 Answers2

14

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

Ole V.V.
  • 81,772
  • 15
  • 137
  • 161
3

Concurrency is not the same thing as parallel computing. Two activities (e.g., two threads) happen concurrently if both have been started before either one of them is finished. You don't need multiple CPUs for that to happen.

But also note what @ernest_k said in a comment: You don't even need to have more than one thread in order for your program to throw a ConcurrentModificationException. All you need to do is create an iterator for some collection, then modify the collection, and then try to continue using the iterator after you've done the modification. That is to say, you'll get the exception if you modify the collection concurrently with an iteration.

Solomon Slow
  • 25,130
  • 5
  • 37
  • 57