Search⌘ K

CopyOnWriteArrayList: Internal Working

Explore how CopyOnWriteArrayList maintains thread safety by using a ReentrantLock and copying an internal array for modifications. Learn the role of the backarray and copied array in preventing concurrency issues and why this collection suits mostly read-heavy scenarios with minimal writes.

We'll cover the following...

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:

...