Can a single core processor still throw ConcurrentModificationException?

我的梦境 提交于 2020-12-12 05:56:47

问题


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.


回答1:


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




回答2:


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.



来源:https://stackoverflow.com/questions/64635319/can-a-single-core-processor-still-throw-concurrentmodificationexception

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!