How to handle ConcurrentModificationException in Android
Solution 1
Try using java.util.concurrent.CopyOnWriteArrayList
instead of ArrayList
Solution 2
Seems from the comments that your ArrayList<Collectable>
is accessed from the onDraw()
method in one thread, by the UI, concurrently with you removing items from it in another thread.
So, why not just wrap both accessors in a
synchronized(array_list_name)
{
// UI access code or item removal code
}
Note that this might make your UI laggy if removing items takes a long time. If this is the case, consider making a list of all item indexes to be removed, and remove them in a tight synchronized loop after iterating over the whole list.
Update
It seems to me your whole code snippet could be simplified to just:
synchronized(array_list_name)
return array_list_name.remove(id);
Solution 3
Have you ever thought to use Vector List ? If you need a thread-safe implementation, you should use Vector
instead of ArrayList
.
Vector
list's usage is same with ArrayList
. Just change its type with Vector
.
Unsafe usage
ArrayList<FutureTask> futureTasks;
Change with
Vector<FutureTask> futureTasks;
That's all.
Related videos on Youtube
dinesh707
Updated on June 01, 2022Comments
-
dinesh707 about 2 years
Im trying to delete item from a
ArrayList
. Some times it pops an exception,java.util.ConcurrentModificationException
.First I tried to remove them by
array_list_name.remove(i)
, but it failed and some people were asked to use Iterator instead. So my current code is as follows:for (Iterator<Collectable> iter = array_list_name.iterator(); iter.hasNext();) { Collectable s = iter.next(); if (s.equals(array_list_name.get(id))){ iter.remove(); return true; } }
And I call
array_list_name
insideonDraw()
function in view. My view is aSurfaceView
. Can anyone suggest me how to delete items fromArrayList
without getting this error?-
Xion almost 13 yearsYes,
onDraw
is called in the UI thread so it might be invoked at the same time as item removal in the other thread. -
Kai almost 13 yearsSo that is the problem, see the API:
The behavior of an iterator is unspecified if the underlying collection is modified while the iteration is in progress...
-
-
Kai almost 13 yearsBut this removes the element in the
copy
. The asker might want the element removed inarray_list_name
. If you remove it by its index you can't be sure you get the right element, because the List might have changed. -
xarlymg89 over 3 yearsThis is by far the best answer on this thread. Using a class as
Vector
that was intented precisely for concurrent usage is the right solution. I've already used in my own project, where I faced a similar problem and was gettingConcurrentModificationException
s. Thanks a lot!