[英]Concurrent updates on Collection
I am developing a System and it has ArrayList
that access in several places(inserting, removing and updates the values). 我正在开发一个System,它具有
ArrayList
,可以在几个地方访问(插入,删除和更新值)。 Due to access of ArrayList
in several places when i run the program it gives Concurrent update error. 由于在我运行程序时在多个位置访问
ArrayList
,因此出现并发更新错误。
Instead of ArrayList
I can use Vector
because Vector
is synchronized. 我可以使用
Vector
代替ArrayList
因为Vector
是同步的。 But if i use Vector
will It be cause to decrease the performance of the system? 但是,如果我使用
Vector
,会导致系统性能下降吗? 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. 还有一件事:您的ConcurrentModificationException可能不是通过两个线程从实际的并发修改中产生的。 There is another possible reason:
还有另一个可能的原因:
While iterating over the ArrayList, you might delete an element. 在遍历ArrayList时,您可以删除一个元素。 If you try this
如果你尝试这个
Object o = iterator.next()
if(someCondition)
arrayList.remove(o)
in a single Thread, you will get a ConcurrentModificationException. 在单个线程中,您将获得ConcurrentModificationException。 In that case you will have to use ListIterator and it's remove method.
在这种情况下,您将必须使用ListIterator,并且它是remove方法。
Have you considered the CopyOnWriteArrayList ? 您是否考虑过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.
ArrayList的线程安全变体,其中所有可变操作(添加,设置等)都通过对基础数组进行全新复制来实现。
As ever, I would not worry too much about efficiency until you know it's a problem. 与以往一样,除非您知道这是一个问题,否则我不会太担心效率。
See Collections#synchronizedCollection(Collection) . 请参见Collections#synchronizedCollection(Collection) 。 This will return a synchronized
ArrayList
that you can use to safely add/remove/update elements in the list. 这将返回一个同步的
ArrayList
,可用于安全地添加/删除/更新列表中的元素。
You can also synchronize your ArrayList on each access: 您还可以在每次访问时同步ArrayList:
synchronize(myList)
{
myList.add(object);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.