What is the difference between CopyOnWritearraylist
and Collections.synchronizedList(..)
? When should one be preferred over the other.
CopyOnWriteArrayList is synchronized. ArrayList is not thread safe. CopyOnWriteArrayList is thread safe. ArrayList iterator is fail-fast and ArrayList throws ConcurrentModificationException if concurrent modification happens during iteration.
CopyOnWriteArrayList is used to synchronize the ArrayList. The Java 1.2 version first introduced the Synchronized ArrayList. The Java 1.5 version first introduced the CopyOnWriteArrayList. The Synchronized ArrayList should be used when there are more write operations than reading operations in ArrayList.
Non synchronized -It is not-thread safe and can't be shared between many threads without proper synchronization code. While, Synchronized- It is thread-safe and can be shared with many threads.
CopyOnWriteArrayList is a thread-safe variant of ArrayList where operations which can change the ArrayList (add, update, set methods) creates a clone of the underlying array. CopyOnWriteArrayList is to be used in a Thread based environment where read operations are very frequent and update operations are rare.
CopyOnWriteArrayList
list should be used when the number of reads vastly outnumber the number of writes. This is because you are trading unnecessary synchronization for expensive array copying on each write.
For example, when you have a List
of event listeners in a multi-threaded environment, you'd want to use CopyOnWriteArrayList
, because
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