简体   繁体   中英

Concurrent updates on Collection

I am developing a System and it has ArrayList that access in several places(inserting, removing and updates the values). Due to access of ArrayList in several places when i run the program it gives Concurrent update error.

Instead of ArrayList I can use Vector because Vector is synchronized. But if i use Vector will It be cause to decrease the performance of the system? Give me Ideas. How I can solve this issue?

This is part of the exception I get:

].[localhost].[/uckt].[Faces Servlet]] (http-127.0.0.1-8080-144) 
Servlet.service() for servlet Faces Servlet threw exception: java.util.ConcurrentModificationException
at java.util.ArrayList$Itr.checkForComodification(Unknown Source) [:1.7.0_02]
at java.util.ArrayList$Itr.next(Unknown Source) [:1.7.0_02] 

There is one more thing: Your ConcurrentModificationException might not spawn from an actual concurrent modification through two Threads. There is another possible reason:

While iterating over the ArrayList, you might delete an element. If you try this

Object o = iterator.next()
if(someCondition)
    arrayList.remove(o)

in a single Thread, you will get a ConcurrentModificationException. In that case you will have to use ListIterator and it's remove method.

Have you considered the CopyOnWriteArrayList ?

A thread-safe variant of ArrayList in which all mutative operations (add, set, and so on) are implemented by making a fresh copy of the underlying array.

As ever, I would not worry too much about efficiency until you know it's a problem.

See Collections#synchronizedCollection(Collection) . This will return a synchronized ArrayList that you can use to safely add/remove/update elements in the list.

You can also synchronize your ArrayList on each access:

synchronize(myList)
{
  myList.add(object);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM