Search

Monday, June 1, 2015

Difference between synchronized ArrayList and CopyOnWriteArrayList in Java?

Though both synchronized ArrayList and CopyOnWriteArrayList provides you thread-safety and you can use both of them when your list is shared between multiple threads, there is a subtle difference between them, Synchronized ArrayList is a synchronized collection while CopyOnWriteArrayList is a concurrent collection. What this means? It means is that CopyOnWriteArrayList is designed keeping concurrency in mind and it is more scalable than synchronized ArrayList if  list is primarily used for reading. You know that ArrayList is not synchronized, so you cannot directly use it in a multi-threaded environment where you list is accessed and modified by multiple threads. In order to use ArrayList in such environment, you need to first get a synchronized list by calling Collections.synchronizedList(). This list achieves thread-safety by locking the whole collection, which means if one thread is reading from list and other is also reading from list, they will go one by one, but you know that multiple thread can read from object without any issue. CopyOnWriteArrayList leverages this knowledge and provides reading without lock, which means a much better performance if there are more reader threads and write is happening quite low. In short, main difference between synchronized ArrayList and CopyOnWriteArrayList comes form the fact how they achieve thread safety and how scalable they are.
Read more »

No comments:

Post a Comment