How to handle ConcurrentModificationException in Android

I am trying to remove an element from an ArrayList. Sometimes it throws an exception, "java.util.ConcurrentModificationException".

At first I tried to delete them using array_list_name.remove (i), but this did not succeed, and some people were asked to use Iterator. 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" inside the onDraw () function. my view is SurfaceView. Can anyone suggest me remove elements from ArrayList without getting this error.

+6
source share
4 answers

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

+7
source

It looks like the comments that your ArrayList<Collectable> receives from the onDraw() method in one thread, by the user interface at the same time as deleting elements from it in another thread.

So why not just wrap both accessors in

 synchronized(array_list_name) { // UI access code or item removal code } 

Please note that this can lead to a delay in the user interface if deleting items takes a long time. If so, consider making a list of all the indexes of the items you want to remove, and delete them in a narrow, synchronized loop after iterating through the entire list.

Update

It seems to me that your whole piece of code can be simplified:

 synchronized(array_list_name) return array_list_name.remove(id); 
+6
source

You can create a protective copy of the list as follows:

 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; } } 
0
source

Have you ever considered using the Vector List ? If you need a thread safe implementation, you should use Vector instead of ArrayList . Using Vector is the same with ArrayList . Just change its type to Vector .

Unsafe use

 ArrayList<FutureTask> futureTasks; 

Edit with

 Vector<FutureTask> futureTasks; 

What all.

0
source

Source: https://habr.com/ru/post/892299/


All Articles