The Java programming language provides several concurrent collections for applications in which multiple threads access shared data. The CopyOnWriteArrayList class is one of them.
What Does Copy on Write Means?
When instantiating the CopyOnWriteArrayList class, we get a list, that its elements are internally stored in an array. Whenever the list is modified, a new copy of that array is created and updated accordingly (instead of changing the existing array directly). Once the modifications are completed, the list starts using the new array (instead of the old one).
Typical Use Cases
Using theCopyOnWriteArrayList class fits best when using collections, such as:
- event listeners
- subscribers
- observers
- configuration listeners
- callback registrations
- relatively stable shared lists
These collections often change rarely but are read repeatedly by many threads.
The Main Trade-Off
The design of CopyOnWriteArrayList deliberately exchanges write performance for simpler and safer concurrent reads.
The Internal Lock
TheCopyOnWriteArrayList class uses an internal lock for mutating operations such as add() and remove(). If a thread tries to add or remove an item that thread will hold the lock which will prevent any other thread to add or remove an item at the same time.
When many threads frequently read a relatively stable list, using the CopyOnWriteArrayList can be an excellent choice. When modifications are frequent, a different concurrent collection or synchronization strategy might be more suitable.







