gpt4 book ai didi

java - CopyOnWriteArrayList 适用于什么情况?

转载 作者:IT老高 更新时间:2023-10-28 13:51:56 25 4
gpt4 key购买 nike

我正在学习 CopyOnWriteArrayList类。

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

所以如果系统并发高,大部分线程的 Action 都是读不写,最好使用CopyOnWriteArrayList

最佳答案

link 中所述:

CopyOnWriteArrayList是 Java 5 Concurrency API 中引入的并发 Collection 类,以及它在 Java 中流行的表亲 ConcurrentHashMap

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

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.

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();

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

关于java - CopyOnWriteArrayList 适用于什么情况?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17853112/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com