How to handle ConcurrentModificationException in Android

為{幸葍}努か 提交于 2019-12-05 06:13:06
Murat Can ALPAY

Try using java.util.concurrent.CopyOnWriteArrayList instead of ArrayList

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);

You could create a defensive copy of the list like so:

List copy = new ArrayList(array_list_name);
for (Iterator<Collectable> iter = copy.iterator(); iter.hasNext();) {
   Collectable s = iter.next();
   if (s.equals(copy.get(id))){
       iter.remove();
       return true;
   }
}

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.

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