CopyOnWriteArrayList
The CopyOnWriteArrayList instance behaves like an implementation of List, which allows multiple simultaneous reads, as well as for reading at the same time as writing. The way this is done is to make a new copy of the list every time it is changed.
- Reading does not block and effectively pays only the cost of the changed reading.
- Records do not block reading (or vice versa), but only one record can appear at once.
- Unlike
ConcurrentHashMap , write operations that write to or access multiple items in a list (e.g. addAll() , retainAll() ) will be atomic.
During a write operation, the array must be completely locked against other write operations. (The standard implementation uses ReentrantLock .) However, this means that, as already mentioned, operations involving multiple locations can be atomic. That is, if one thread adds multiple items to the list using addAll (), while another thread calls size (), the thread reading the size will receive a value that reflects or does not include the number of items added to addAll (): it will not be possible to return an intermediate value (provided, of course, that these are only two threads accessing the list!).
CopyOnWriteArrayList is designed for cases where reads hugely outnumber writes .
CopyOnWriteArraySet
Another CopyOnWriteArraySet class CopyOnWriteArraySet built on top of CopyOnWriteArrayList . Like his colleague on the list, it is intended for cases where the set contains only a few elements and where the reading significantly exceeds the number of records.
Link: Java Record Copy Collections
source share