Case 1: This does not cause ConcurrentModificationException
?. Can anyone tell me why does this not cause ConcurrentModificationException.
public class UpdatePeople {
List < People > records = new ArrayList < People > ();
public class AsyncTask extends AsyncTask < Void, Void, Boolean > {
List < People > people;
public AsyncTask(List < People > allergy) {
this.people = people;
}@
Override
protected Boolean doInBackground(Void...params) {
List < String > responses = new ArrayList < String > ();
for (People peopleList: this.people) {
}
}
}
}
Case 2: This causes ConcurrentModificationException
as i am trying to access the List of people in my AsyncThread which is not thread safe. I can make my List of People implement CopyOnWriteArrayList
which is thread safe and this should work.
public class UpdatePeople {
List < People > records = new ArrayList < People > ();
public class AsyncTask extends AsyncTask < Void, Void, Boolean > {
@
Override
protected Boolean doInBackground(Void...params) {
List < String > responses = new ArrayList < String > ();
for (People peopleList: records) {
}
}
}
}
- Can anyone explain me what is exactly happening in
case 1
. I am not able to understand how this solves theConcurrentModificationException
issue. - Is the case 2 changing the implementation from
ArrayList
toCopyOnWriteArrayList
recommended?
Adding the exception:
05-28 20:34:21.073: E/XXX(904): Uncaught exception is: 05-28 20:34:21.073: E/XXX(904): java.lang.RuntimeException: An error occured while executing doInBackground() 05-28 20:34:21.073: E/XXX(904): at android.os.AsyncTask$3.done(AsyncTask.java:299) 05-28 20:34:21.073: E/XXX(904): at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273) 05-28 20:34:21.073: E/XXX(904): at java.util.concurrent.FutureTask.setException(FutureTask.java:124) 05-28 20:34:21.073: E/XXX(904): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307) 05-28 20:34:21.073: E/XXX(904): at java.util.concurrent.FutureTask.run(FutureTask.java:137) 05-28 20:34:21.073: E/XXX(904): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230) 05-28 20:34:21.073: E/XXX(904): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076) 05-28 20:34:21.073: E/XXX(904): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569) 05-28 20:34:21.073: E/XXX(904): at java.lang.Thread.run(Thread.java:856) 05-28 20:34:21.073: E/XXX(904): Caused by: java.util.ConcurrentModificationException 05-28 20:34:21.073: E/XXX(904): at java.util.ArrayList$ArrayListIterator.next(ArrayList.java:569)