Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 672
ZeNstok Avatar asked Aug 04 '26 20:08

ZeNstok


2 Answers

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

like image 55
Ole V.V. Avatar answered Aug 06 '26 10:08

Ole V.V.


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.

like image 23
Solomon Slow Avatar answered Aug 06 '26 11:08

Solomon Slow



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!