简体   繁体   English

什么java列表适合addAll和clear上的线程安全

[英]What java List is suitable for thread safe on addAll and clear

I only call addAll and clear of the List, but need it to thread-safe, is there any existing List for this ? 我只调用addAll并清除List,但是需要它进行线程安全,为此是否有任何现有List? Thanks 谢谢

List is not-synchronized. 列表未同步。 So it is not thread-safe. 因此它不是线程安全的。 If you want it as thread-safe means it is possible to make the list as thread-safe, you can use the 如果您希望将其设为线程安全的,则可以将列表设为线程安全的,则可以使用

Collections.synchronizedList(List list) Collections.synchronizedList(列表列表)

A list created using Collections.synchronizedList(List list) will satisfy those requirements, provided that the synchronized list is the target object in the addAll(...) call, and never the parameter. 使用Collections.synchronizedList(List list)创建的Collections.synchronizedList(List list)将满足这些要求, 前提是同步列表是addAll(...)调用中的目标对象,而不是参数。

If the synchronized list (created as above) is the argument, then the problem is that addAll(list) iterates the argument list , and iterating a synchronized list is not atomic. 如果同步列表(如上创建)是参数,则问题在于addAll(list)迭代参数list ,而迭代同步列表不是原子的。 If another thread updates list while it is being added, the you are liable to get a ConcurrentModificationException . 如果在添加另一个线程时更新了list ,则您有可能会收到ConcurrentModificationException

If you need to do the addAll(list) in a thread-safe fashion in the face of concurrent updates to list , then you need to make list a CopyOnWriteArrayList . 如果需要在面对对list的并发更新时以线程安全的方式执行addAll(list) ,则需要将listCopyOnWriteArrayList

There is a concurrent list implementation in java.util.concurrent. java.util.concurrent中有一个并发列表实现。 CopyOnWriteArrayList in particular. 特别是CopyOnWriteArrayList

如果要使用现有列表作为同步列表,请访问Collections.synchronizedList(list)或创建目标列表,然后可以使用CopyOnWriteArrayList

CopyOnWriteArrayList is a concurrent replacement for synchronizedList that offers better concurrency in some common situations & eliminates the need to lock or copy the collection during iteration. CopyOnWriteArrayList是SynchronizedList的并发替代,它在某些常见情况下提供了更好的并发性,并且消除了在迭代过程中锁定或复制集合的需要。

The copy on write collections derive their thread safety from the fact that as an effectively immutable object is properly published, no further synchronization is required when accessing it. 写入时复制集合的线程安全性源于以下事实:由于正确发布了有效的不可变对象,因此在访问该对象时不需要进一步的同步。 They implement mutability by creating & republishing a new copy of the collection everytime it is modified. 它们通过在每次修改集合时创建并重新发布该集合的新副本来实现可变性。 The collection does not throw ConcurrentModificationException regardless of subsequent modifications. 无论后续修改如何,该集合都不会引发ConcurrentModificationException。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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