How to handle ConcurrentModificationException in Android
Try using java.util.concurrent.CopyOnWriteArrayList
instead of ArrayList
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.
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);