控制对 Java 集合的并发访问的最佳方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/561671/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Best way to control concurrent access to Java collections
提问by PhiLho
Should I use old synchronized Vector collection, ArrayList with synchronized access or Collections.synchronizedList or some other solution for concurrent access?
我应该使用旧的同步 Vector 集合、同步访问的 ArrayList 还是 Collections.synchronizedList 或其他一些并发访问解决方案?
I don't see my question in Related Questions nor in my search (Make your collections thread-safe?isn't the same).
我在相关问题和搜索中都没有看到我的问题(使您的集合线程安全?不一样)。
Recently, I had to make kind of unit tests on GUI parts of our application (basically using API to create frames, add objects, etc.). Because these operations are called much faster than by a user, it shown a number of issues with methods trying to access resources not yet created or already deleted.
最近,我不得不对我们应用程序的 GUI 部分进行某种单元测试(基本上使用 API 来创建框架、添加对象等)。由于这些操作的调用速度比用户调用的速度快得多,因此尝试访问尚未创建或已删除的资源的方法会出现许多问题。
A particular issue, happening in the EDT, came from walking a linked list of views while altering it in another thread (getting a ConcurrentModificationException among other problems). Don't ask me why it was a linked list instead of a simple array list (even less as we have in general 0 or 1 view inside...), so I took the more common ArrayList in my question (as it has an older cousin).
在 EDT 中发生的一个特殊问题来自在另一个线程中更改视图的链接列表时遍历它(在其他问题中获得 ConcurrentModificationException)。不要问我为什么它是一个链表而不是一个简单的数组列表(甚至更少,因为我们内部通常有 0 或 1 个视图......),所以我在我的问题中采用了更常见的 ArrayList(因为它有一个堂兄)。
Anyway, not super familiar with concurrency issues, I looked up a bit of info, and wondered what to choose between the old (and probably obsolete) Vector (which has synchronized operations by design), ArrayList with a synchronized (myList) { }
around critical sections (add/remove/walk operations) or using a list returned by Collections.synchronizedList (not even sure how to use the latter).
无论如何,我对并发问题不是很熟悉,我查了一些信息,想知道在旧的(可能已经过时的)Vector(它按设计具有同步操作)、带有synchronized (myList) { }
周围关键部分的ArrayList (添加/删除/walk 操作)或使用 Collections.synchronizedList 返回的列表(甚至不确定如何使用后者)。
I finally chose the second option, because another design mistake was to expose the object (getViewList() method...) instead of providing mechanisms to use it.
我最终选择了第二个选项,因为另一个设计错误是公开对象(getViewList() 方法...)而不是提供使用它的机制。
But what are the pros and cons of the other approaches?
但是其他方法的优缺点是什么?
[EDIT] Lot of good advices here, hard to select one. I will choose the more detailed and providing links/food for thoughts... :-) I like Darron's one too.
[编辑] 这里有很多好的建议,很难选择一个。我会选择更详细的,并提供链接/思考的食物...... :-) 我也喜欢 Darron 的。
To summarize:
总结一下:
- As I suspected, Vector (and its evil twin, Hashtable as well, probably) is largely obsolete, I have seen people telling its old design isn't as good as newer collections', beyond the slowness of synchronization forced even in single thread environment. If we keep it around, it is mostly because older libraries (and parts of Java API) still use it.
- Unlike what I thought, Collections.synchronizedXxxx aren't more modern than Vector (they appear to be contemporary to Collections, ie. Java 1.2!) and not better, actually. Good to know. In short, I should avoid them as well.
- Manual synchronization seems to be a good solution after all. There might be performance issues, but in my case it isn't critical: operations done on user actions, small collection, no frequent use.
- java.util.concurrent package is worth keeping in mind, particularly the CopyOnWrite methods.
- 正如我所怀疑的,Vector(以及它的邪恶双胞胎,也可能是 Hashtable)在很大程度上已经过时了,我看到人们说它的旧设计不如新的集合好,除了即使在单线程环境中强制同步的缓慢之外. 如果我们保留它,主要是因为旧的库(和部分 Java API)仍在使用它。
- 与我的想法不同,Collections.synchronizedXxxx 并不比 Vector 更现代(它们似乎与 Collections 更现代,即 Java 1.2!),实际上并没有更好。很高兴知道。简而言之,我也应该避免它们。
- 毕竟手动同步似乎是一个很好的解决方案。可能存在性能问题,但在我的情况下,这并不重要:对用户操作完成的操作、小集合、不频繁使用。
- java.util.concurrent 包值得牢记,尤其是 CopyOnWrite 方法。
I hope I got it right... :-)
我希望我做对了... :-)
采纳答案by Alex Miller
Vector and the List returned by Collections.synchronizedList() are morally the same thing. I would consider Vector to be effectively (but not actually) deprecated and always prefer a synchronized List instead. The one exception would be old APIs (particularly ones in the JDK) that require a Vector.
Vector 和 Collections.synchronizedList() 返回的 List 在道德上是一回事。我认为 Vector 被有效地(但实际上并未)弃用,并且总是更喜欢同步列表。一个例外是需要 Vector 的旧 API(尤其是 JDK 中的 API)。
Using a naked ArrayList and synchronizing independently gives you the opportunity to more precisely tune your synchronization (either by including additional actions in the mutually exclusive block or by putting together multiple calls to the List in one atomic action). The down side is that it is possible to write code that accesses the naked ArrayList outside synchronization, which is broken.
使用裸 ArrayList 并独立同步使您有机会更精确地调整同步(通过在互斥块中包含其他操作或将多个对 List 的调用放在一个原子操作中)。不利的一面是,可以编写在同步之外访问裸 ArrayList 的代码,这已被破坏。
Another option you might want to consider is a CopyOnWriteArrayList, which will give you thread safety as in Vector and synchronized ArrayList but also iterators that will not throw ConcurrentModificationException as they are working off of a non-live snapshot of the data.
您可能要考虑的另一个选项是 CopyOnWriteArrayList,它将为您提供 Vector 和同步 ArrayList 中的线程安全性,以及不会抛出 ConcurrentModificationException 的迭代器,因为它们正在处理数据的非实时快照。
You might find some of these recent blogs on these topics interesting:
您可能会发现有关这些主题的一些近期博客很有趣:
回答by matt b
I don't believe that the Iterator
returned by a Vector is in any way synchronized - meaning that Vector
can't guarantee (on it's own) that one thread isn't modifying the underlying collection while another thread is iterating through it.
我不相信Iterator
Vector 返回的以任何方式同步 - 这意味着Vector
不能保证(靠它自己)一个线程不会修改底层集合,而另一个线程正在迭代它。
I believe that to ensure that iterating is thread-safe, you will have to handle the synchronization on your own. Assuming that the same Vector/List/object is being shared by multiple threads (and thus leading to your issues), can't you just synchronize on that object itself?
我相信为了确保迭代是线程安全的,您必须自己处理同步。假设同一个 Vector/List/object 被多个线程共享(从而导致您的问题),您不能只在该对象本身上进行同步吗?
回答by jcrossley3
I can't think of a good reason to ever prefer Vector
over ArrayList
. List operations on a Vector
are synchronized, meaning multiple threads can alter it safely. And like you say, ArrayList's operations can be synchronized using Collections.synchronizedList
.
我想不出一个很好的理由来喜欢Vector
over ArrayList
。对 a 的列表操作Vector
是同步的,这意味着多个线程可以安全地更改它。就像你说的,ArrayList 的操作可以使用Collections.synchronizedList
.
Remember that even when using synchronized lists, you will still encounter ConcurrentModificationExceptions
if iterating over the collection while it's being modified by another thread. So it's important to coordinate that access externally (your second option).
请记住,即使在使用同步列表时,ConcurrentModificationExceptions
如果在另一个线程修改集合时迭代集合,您仍然会遇到。因此,在外部协调该访问非常重要(您的第二个选择)。
One common technique used to avoid the iteration problem is to iterate over immutable copies of the collection. See Collections.unmodifiableList
用于避免迭代问题的一种常用技术是迭代集合的不可变副本。看Collections.unmodifiableList
回答by richs
i would always go to the java.util.concurrent (http://java.sun.com/javase/6/docs/api/java/util/concurrent/package-summary.html) package first and see if there is any suitable collection. the java.util.concurrent.CopyOnWriteArrayList class is good if you are doing few changes to the list but more iterations.
我总是先去 java.util.concurrent ( http://java.sun.com/javase/6/docs/api/java/util/concurrent/package-summary.html) 包,看看是否有合适的收藏。java.util.concurrent.CopyOnWriteArrayList 类很好,如果您对列表进行很少的更改但进行更多的迭代。
also I don't believe Vector and Collections.synchronizedList will prevent ConcurrentModificationException.
我也不相信 Vector 和 Collections.synchronizedList 会阻止 ConcurrentModificationException。
if you don't find a suitable collection then you'd have to do your own synchronization, and if you don't want to hold a lock when iterating you may want to consider making a copy and iterating the copy.
如果您没有找到合适的集合,那么您必须进行自己的同步,如果您不想在迭代时持有锁,您可能需要考虑制作副本并迭代副本。
回答by Michael Borgwardt
The safest solution is to avoid concurrent access to shared data altogether. Instead of having non-EDT threads operate on the same data, have them call SwingUtilities.invokeLater()
with a Runnable that performs the modifications.
最安全的解决方案是完全避免并发访问共享数据。不要让非 EDT 线程对相同的数据进行操作,而是让它们调用SwingUtilities.invokeLater()
执行修改的 Runnable。
Seriously, shared-data concurrency is a viper's nest where you'll never know if there isn't another race condition or deadlock hiding somewhere, biding its time to bite you in the ass at the worst possible occasion.
说真的,共享数据并发是一个毒蛇的巢穴,在那里你永远不会知道是否有另一个竞争条件或死锁隐藏在某处,等待时机在最糟糕的情况下咬你的屁股。
回答by Javamann
CopyOnWriteArrayList is worthwhile to look at. It is designed for a list that is usually read from. Every write would cause it to create an new array behind the covers so those iterating across the array would not get a ConcurrentModificationException
CopyOnWriteArrayList 值得一看。它是为通常读取的列表而设计的。每次写入都会导致它在幕后创建一个新数组,因此那些遍历数组的人不会得到 ConcurrentModificationException
回答by Darron
I strongly recommend the book "Java Concurrency in Practice".
我强烈推荐《Java 并发实践》一书。
Each of the choices has advantages/disadvantages:
每个选择都有优点/缺点:
- Vector - considered "obsolete". It may get less attention and bug fixes than more mainstream collections.
- Your own synchronization blocks - Very easy to get incorrect. Often gives poorer performance than the choices below.
- Collections.synchronizedList() - Choice 2 done by experts. This is still not complete, because of multi-step operations that need to be atomic (get/modify/set or iteration).
- New classes from java.util.concurrent - Often have more efficient algorithms than choice 3. Similar caveats about multi-step operations apply but tools to help you are often provided.
- 矢量 - 被认为是“过时的”。与更主流的收藏相比,它可能会得到较少的关注和错误修复。
- 您自己的同步块 - 很容易出错。通常比下面的选择提供更差的性能。
- Collections.synchronizedList() - 由专家完成的选择 2。这仍然不完整,因为需要原子的多步操作(获取/修改/设置或迭代)。
- java.util.concurrent 中的新类 - 通常具有比选项 3 更有效的算法。关于多步操作的类似警告适用,但通常会提供帮助您的工具。