How do copy on write collections provide thread-safety and in which scenarios are they useful to implement?
CopyOnWriteArrayList
An instance of CopyOnWriteArrayList behaves as a List implementation that allows multiple concurrent reads, and for reads to occur concurrently with a write. The way it does this is to make a brand new copy of the list every time it is altered.
ConcurrentHashMap
, write operations that write or access multiple elements in the list (such as addAll()
, retainAll()
) will be atomic.During a write operation, the array must be locked completely against other writes. (The standard implementation uses a ReentrantLock.) However, this does mean that as mentioned, operations affecting multiple locations can be atomic. That is, if one thread adds several items to the list with addAll() while another thread calls size(), the thread reading the size will get a value that either reflects or not the number of elements added in addAll(): there'll be no possibility of an intermediate value returned (provided of course that these are the only two threads accessing the list!).
CopyOnWriteArrayList is designed for cases where reads hugely outnumber writes
.
CopyOnWriteArraySet
Another class, CopyOnWriteArraySet
is build on top of CopyOnWriteArrayList
. Like its list counterpart, it is designed for cases where the set contains only a few elements and where reads greatly outnumber writes.
Reference: Java copy-on-write collections
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With