CopyOnWriteArrayList: Introduction
Let's discuss a thread-safe list called CopyOnWriteArrayList.
We'll cover the following...
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 ...