CopyOnWriteArrayList: Internal Working

Let's discuss the internal workings of CopyOnWriteArrayList.

The internal workings of CopyOnWriteArrayList is a very important topic for Java interviews. In this lesson, we will see how CopyOnWriteArrayList provides thread-safety.

CopyOnWriteArrayList is internally backed by an array, so let’s call it backarray for the purpose of understanding. Throughout this lesson, wherever we use the term backarray, it means the array in which all the elements added to the CopyOnWriteArrayList is maintained.

There is a ReentrantLock defined in the CopyOnWriteArrayList as shown below:

/** The lock protecting all mutators */
final transient ReentrantLock lock = new ReentrantLock();

When a new element is added in a CopyOnWriteArrayList then the following procedure takes place:

  1. The thread that is adding the element acquires a lock on the lock object using the lock.lock() method. If some other thread tries to add an element to the list, then it will not get access.
  2. The thread that has acquired the lock will then make the copy of the backarray. So as shown in the below snippet, a new array is created and all the elements from the backarray are added to this new array. The size of this new array is one more than the backarray.
Object[] newElements = Arrays.copyOf(elements, len + 1);
  1. Now, the element that needs to be added will be added at the end of this newly copied array.
newElements[len] = e;
  1. Finally the backarray will now be pointed to this new array and the lock will be released. In this way, a new element is added to the CopyOnWriteArrayList in a thread-safe manner.

Get hands-on with 1400+ tech skills courses.