CopyOnWriteArrayList in Java

Spread the love

CopyOnWriteArrayList data structure in Java is an advancement over the ArrayList data Structure

It is a thread safe variant of the ArrayList data structure in which a separate copy is created when the CopyOnWriteArrayList needs to be modified and insert/update/delete operations are done on that copy.

The CopyOnWriteArrayList class implements following interfaces:

-> List

->RandomAccess

->Cloneable

->Serializable

CopyOnWriteArrayList Important Points:

  • It works on a separate copy of the actual list when manipulations are done on the list. So it becomes a costly affair.
  • Since it is creates a copy, each thread who are working on that list can work without any problems. It will not throw an ConcurrentModificationException since threads work on separate copies of the list. This is the main benefit over the ArrayList class.
  • Get operation is faster as it implements the RandomAccess interface. It implements the List interface as well and thus provide all functionalities available in ArrayList class.
  • Since it creates a new copy of array everytime iterator is created, performance is slower compared to ArrayList.

Ways to initialise ->

//Empty list
CopyOnWriteArrayList c = new CopyOnWriteArrayList();
//Using another Collection
CopyOnWriteArrayList c = new CopyOnWriteArrayList(Collection coll);
//Using an object array
CopyOnWriteArrayList c = new CopyOnWriteArrayList(Object[] obj);

Let’s look at the code implementation of CopyOnWriteArrayList:



class CopyOnWriteArrayListImpl {
    public static void main(String[] args)
    {
 
        CopyOnWriteArrayList<String> list
            = new CopyOnWriteArrayList<>();
 
        // Initial Iterator which is empty and creating an iterator over it
        Iterator itr = list.iterator();
        list.add("James");
        System.out.println("List has: ");
        while (itr.hasNext())
            System.out.println(itr.next());
 
        //Another Iterator after adding an element
        itr = list.iterator();
        System.out.println("List has:");
        while (itr.hasNext())
            System.out.println(itr.next());
    }
}

O/P:
List has: 
List has:
James

As per the code, iterator was created on an empty list and worked on an empty clone copy of that.

The 2nd iterator was created on an non empty list and it worked on an non empty list clone copy of that.