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 theCopyOnWriteArrayList
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:
- The thread that is adding the element acquires a lock on the
lock
object using thelock.lock()
method. If some other thread tries to add an element to the list, then it will not get access. - 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);
- Now, the element that needs to be added will be added at the end of this newly copied array.
newElements[len] = e;
- 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.