Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do copy on write collections provide thread-safety? [duplicate]

How do copy on write collections provide thread-safety and in which scenarios are they useful to implement?

like image 468
prvn Avatar asked Sep 26 '22 16:09

prvn


1 Answers

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.

  1. Reads do not block, and effectively pay only the cost of a volatile read.
  2. Writes do not block reads (or vice versa), but only one write can occur at once.
  3. Unlike 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

like image 118
YoungHobbit Avatar answered Sep 30 '22 08:09

YoungHobbit