javacollections

In what situations is the CopyOnWriteArrayList suitable?


I am learning about the CopyOnWriteArrayList class.

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


Solution

  • As stated on this link:

    CopyOnWriteArrayList is a concurrent Collection class introduced in Java 5 Concurrency API along with its popular cousin ConcurrentHashMap in Java. CopyOnWriteArrayList implements List interface like ArrayList, Vector and LinkedList but it is a thread-safe collection and it achieves its thread-safety in a slightly different way than Vector or other thread-safe collection class. As the name suggests CopyOnWriteArrayList creates a copy of underlying ArrayList with every mutation operation e.g. add, remove, or when you set values. That's why it is only suitable for a small list of values which are read frequently but modified rarely e.g. a list of configurations.

    Normally CopyOnWriteArrayList is very expensive because it involves costly Array copy with every write operation but it's very efficient if you have a List where Iteration outnumbers 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 a separate copy of ArrayList. Consequently all the updates made on CopyOnWriteArrayList is not available to Iterator.

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

    That being said, updating this collection a lot 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 when you are doing upwards of 90+% reads.