Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: CopyOnWriteArrayList vs synchronizedList

What is the difference between CopyOnWritearraylist and Collections.synchronizedList(..)? When should one be preferred over the other.

like image 941
DeeEs Avatar asked Oct 01 '10 19:10

DeeEs


People also ask

What is difference between ArrayList and CopyOnWriteArrayList?

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.

Is CopyOnWriteArrayList synchronized?

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.

What is difference between synchronized and non synchronized in Java?

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.

What is CopyOnWriteArrayList in Java?

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.


1 Answers

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

  • events are fired, and hence the list is iterated very often
  • event listeners are registered rarely
like image 165
Bozho Avatar answered Oct 31 '22 05:10

Bozho