The ArrayList and LinkedList data structures are not thread-safe. This means that if we are working in an environment where multiple threads are simultaneously adding or removing elements from a list, it may not work as intended. If a thread is iterating over a list and, in the meantime, another thread tries to add an element to the list, then ConcurrentModificationException will be thrown.

Now, if we want to use a list in a multi-threaded environment, we have few options. The first option is using a Vector. The Vector is a legacy class in which all the methods are synchronized. Since for each operation, such as add or remove, the entire list is locked, it is slow. Hence it is no longer used.

The second option is making our list thread-safe by using the Collections.synchronizedList() method. The problem with this method is that it also locks the entire list for each operation. So, there is no performance benefit.

To overcome these issues CopyOnWriteArrayList was introduced. This is a thread-safe list with high performance. In this lesson, we will focus on how it is used.

Get hands-on with 1400+ tech skills courses.