CopyOnWriteArrayList 适用于哪些情况? [英] In what situations is the CopyOnWriteArrayList suitable?

查看:37
本文介绍了CopyOnWriteArrayList 适用于哪些情况?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习 CopyOnWriteArrayList 类.

  • 复制新数组的目的是什么?
  • 是否让其他线程读取数组?

所以如果一个系统并发度高,并且大部分线程的动作都是读而不是写,最好使用CopyOnWriteArrayList.

So if a system has high concurrency and most of the threads' actions are reading not writing, it is better to use CopyOnWriteArrayList.

推荐答案

如上所述 链接:

CopyOnWriteArrayList 是并发Java 5 Concurrency API 中引入的集合类及其在 Java 中流行的ConcurrentHashMap.

CopyOnWriteArrayList is a concurrent Collection class introduced in Java 5 Concurrency API along with its popular cousin ConcurrentHashMap in Java.

CopyOnWriteArrayList 实现了类似 ArrayListVectorLinkedList 的 List 接口,但它是一个线程安全的集合,它以与 Vector 或其他线程安全集合类略有不同的方式实现其线程安全.

CopyOnWriteArrayList implements List interface like ArrayList, Vector and LinkedList but its a thread-safe collection and it achieves its thread-safety in a slightly different way than Vector or other thread-safe collection class.

顾名思义,CopyOnWriteArrayList 创建底层的副本带有每个变异操作的 ArrayList,例如添加或设置.一般CopyOnWriteArrayList 非常昂贵,因为它涉及昂贵的每次写入操作时都进行数组复制,但是如果您使用它,它非常有效有一个列表,其中迭代超过突变,例如你主要需要迭代ArrayList,不要经常修改.

As name suggest CopyOnWriteArrayList creates copy of underlying ArrayList with every mutation operation e.g. add or set. Normally CopyOnWriteArrayList is very expensive because it involves costly Array copy with every write operation but its very efficient if you have a List where Iteration outnumber mutation e.g. you mostly need to iterate the ArrayList and don't modify it too often.

CopyOnWriteArrayList 的迭代器是故障安全的,不会抛出ConcurrentModificationException 即使底层一旦迭代开始,CopyOnWriteArrayList 就会被修改,因为迭代器正在对 ArrayList 的单独副本进行操作.因此所有迭代器无法使用 CopyOnWriteArrayList 上的更新.

Iterator of CopyOnWriteArrayList is fail-safe and doesn't throw ConcurrentModificationException even if underlying CopyOnWriteArrayList is modified once Iteration begins because Iterator is operating on separate copy of ArrayList. Consequently all the updates made on CopyOnWriteArrayList is not available to Iterator.

要获得最新的版本,请像 list.iterator();

To get the most updated version do a new read like list.iterator();

话虽如此,大量更新此集合会降低性能.如果您尝试对 CopyOnWriteArrayList 进行排序,您将看到该列表抛出一个 UnsupportedOperationException(对集合设置的排序调用 N 次).仅当读取超过 90% 时才应使用此读取.

That being said, updating this collection alot will kill performance. If you tried to sort a CopyOnWriteArrayList you'll see the list throws an UnsupportedOperationException (the sort invokes set on the collection N times). You should only use this read when you are doing upwards of 90+% reads.

这篇关于CopyOnWriteArrayList 适用于哪些情况?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆