CopyOnWriteArrayList vs SynchronizedList

CopyOnWriteArrayList(Introduced in JDK 1.5) SynchronizedList
Creation List list = new CopyOnWriteArrayList(); List list = new ArrayList();
List syncList = Collections.synchronizedList(list);
Is Thread Safe? YES.

CopyOnWriteArrayList is a thread-safe variant of ArrayList. It is designed for concurrent access from multiple threads. CopyOnWriteArrayList provides a thread-safe alternative for ArrayList same way ConcurrentHashMap provides a thread-safe alternative for HashMap and CopyOnWriteArraySet for HashSet.

YES
How Thread Safety is Achieved? Thread safety is achieved by making a fresh copy of the underlying array with every mutative operations (add, set, and so on). It is evident from the name also Copy on write whenever value is change create a copy. Locks the SynchronizedList for all the operations on the underlying list.Basically it adds a synchronized block for all the operations.For example:Let us look into the add method of the SynchronizedList:

public void add(int index, E element) {
synchronized (mutex) {list.add(index, element);}
}

Iterator fail-safe iterator fail-fast iterator
Performance CopyOnWriteArrayList implements all mutative operations (add, set, and so on) by making a fresh copy of the underlying array. So there is no additional overhead during a read operation but massive overhead during a write operation. Very poor performance as the whole list is locked and only a single thread can access it at a given time.
Memory Overhead YES.

Need to make a fresh copy of underlying list for mutative operations like add, set and so on.

NO.
When to use CopyOnWriteArrayList is a good choice when number of reads is significantly higher than number of writes. Collections.synchronizedList() is a good choice when  writes outnumber reads

Related Articles:

ArrayList vs Vector: Top 8 Basic Differences

ArrayList vs LinkedList

Array vs ArrayList: Choosing the Right Data Structure

Leave a Reply

Your email address will not be published. Required fields are marked *