How can CopyOnWriteArrayList be thread-safe ?
CopyOnWriteArrayList is a thread-safe variant of ArrayList in Java, achieving thread safety through a strategy known as 'Copy-on-Write'. This strategy is suitable for concurrent scenarios with more reads than writes, as each modification operation results in the entire underlying array being copied. Below are the specific implementation details and principles:Copy-on-Write StrategyBasic Principles:Whenever modifications are needed to the contents of a CopyOnWriteArrayList (such as adding, removing, or setting elements), the class does not directly alter the current array.Instead, it first creates a complete copy of the current array and performs the modification on this new copy.After modification, it updates the internal reference to point to the newly modified array.Consequently, traversal operations remain unaffected by modifications because they access the reference to the old array until the reference is updated.Thread Safety:This copy-on-write mechanism ensures that read operations (such as get, iterator, listIterator, etc.) can execute safely without synchronization, as these operations only access the immutable array.Since each modification involves copying the entire array, there is no conflict between write and read operations.The modification operation itself is protected by an internal ReentrantLock (reentrant lock), ensuring that only one thread executes a write operation at a time and maintaining atomicity.ExampleSuppose we have a CopyOnWriteArrayList with initial content [1, 2, 3]. If one thread attempts to add element 4 while another thread simultaneously iterates the list, the scenario unfolds as follows:Adding an Element:Thread A calls add(4).CopyOnWriteArrayList locks, copies the current array [1, 2, 3].Adds 4 to the new array [1, 2, 3], resulting in [1, 2, 3, 4].Updates the internal array reference to point to [1, 2, 3, 4].Unlocks.Iterating Elements:Thread B starts iterating the list simultaneously.Since the write operation occurs on the copied new array, the iterator still references the old array [1, 2, 3], so the iteration process does not observe the change.Iteration completes, yielding elements 1, 2, 3.SummaryCopyOnWriteArrayList avoids read-write conflicts by creating a new copy of the underlying array for each write operation, providing an efficient mechanism for handling concurrent scenarios with more reads than writes. Although this approach sacrifices performance and memory usage during write operations, it offers excellent thread safety and iteration performance when high concurrency on reads and infrequent writes are required.