I have a static method which I am calling from an Asynctask in doInBackGround()
In the method there is this part of code:
ArrayList<Message> messagesList = new ArrayList<Message>();
if (!clearList) {
messagesList.addAll(messages.getMessagesList());
for (Message msg : messagesList) {
if (msg.getId().length() == 0) {
messagesList.remove(msg);
}
}
}
It is sometimes throwing ‘Concurrent modification exception’, I have tried declaring the method as ‘synchronized’ but it still didn’t help, and I cannot declare the block synchronized, since it is a static method and there is no ‘this’ reference.
I have also tried to stop a running asynctask if I need to start another one, but it didn’t help as well.
Help appreciated.
This has nothing to do with synchronization. You’re using an iterator to loop over
messagesList, but then usingremoveto modify it during the iteration. You can’t do that, becauseArrayList‘s iterators fail when the list if modified during iteration. From the docs:Your enhanced
forloop is just syntactic sugar around using anIterator, so you can just make that explicit and then use the iterator’sremovemethod:Alternately, you can just use a simple
forloop running backward and indexing into theArrayList(sinceget(int)is a cheap and constant-time operation on anArrayList, which isn’t true of allLists):