CopyOnWriteArrayList in Java Example - Java @ Desk

Saturday, April 12, 2014

CopyOnWriteArrayList in Java Example

CopyOnWriteArrayList in Java Example

java.util.ArrayList that implements the List interface is not a thread safe implementation. Also the iterator of an ArrayList is fail-fast i.e. it throws ConcurrentModificationException when the list gets modified while the iterator of ArrayList object is traversing or iterating through the List object.

CopyOnWriteArrayList is an implementation that belongs to concurrent family in a Collection framework. Iterator of CopyOnWriteArrayList is fail-safe, hence it does not throw ConcurrentModificationException when the list gets modified while the iterator of CopyOnWriteArrayList object is traversing or iterating through the List object.

How it works? Why CopyOnWriteArrayList does not throw ConcurrentModificationException Exception?
When the Iterator object is created from the CopyOnWriteArrayList object, it gets the seperate copy of ArrayList on which the Iterator iterates. So even if remove or add operations are performed on the CopyOnWriteArrayList object, the ArrayList of the Iterator does not gets modified.

Difference between CopyOnWriteArrayList and ArrayList in Java.
1) ArrayList is not thread safe whereas CopyOnWriteArrayList is a thread safe collection that is used in concurrent applications

2) ArrayList Iterator throws ConcurrentModificationException when the list gets modified during Iteraion. But CopyOnWriteArrayList does not throw any ConcurrentModificationException even if the list gets modified during Iteraion.

3) CopyOnWriteArrayList does not support remove() functionality whereas ArrayList has remove() method

package test;

import java.util.Iterator;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.TimeUnit;

public class CopyOnWriteArrayListExample {
    public static void main(String args[]) {
        final CopyOnWriteArrayList<String> copyOnWriteArrayList = 
            new CopyOnWriteArrayList<String>();
        copyOnWriteArrayList.add("Car Insurance");
        copyOnWriteArrayList.add("Online Accounting Degree");
        copyOnWriteArrayList.add("Insurance");
        copyOnWriteArrayList.add("Personal Loan");
        System.out.println("Original CopyOnWriteArrayList :"
                + copyOnWriteArrayList + "\n");
        // new thread to concurrently modify the list
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    TimeUnit.SECONDS.sleep(2);
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                copyOnWriteArrayList.add("Car Loans");
                System.out
                        .println("\nConcurrently the list got modified in another thread");
                System.out.println("New CopyOnWriteArrayList :"
                        + copyOnWriteArrayList + "\n");
            }
        }).start();

        Iterator<String> failSafeIterator = copyOnWriteArrayList.iterator();
        while (failSafeIterator.hasNext()) {
            System.out.printf("Iterating the List - " + failSafeIterator.next()
                    + "\n");
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
}



As shown in the output below :


1) Original List contains 4 Elements
2) The Iterator object got created on the original list before any modification, so Iterator also contains 4 Elements
3) In between the Iteration, CopyOnWriteArrayList added one element in new thread and the CopyOnWriteArrayList now contains 5 elements
4) But the iterator only displayed 4 elements because Iterator operates on different object of CopyOnWriteArrayList i.e. copy of an CopyOnWriteArrayList object.

Original CopyOnWriteArrayList :[Car Insurance, Online Accounting Degree, Insurance, Personal Loan]

Iterating the List - Car Insurance
Iterating the List - Online Accounting Degree
Iterating the List - Insurance

Concurrently the list got modified in another thread
New CopyOnWriteArrayList :[Car Insurance, Online Accounting Degree, Insurance, Personal Loan, Car Loans]
Iterating the List - Personal Loan







1 comment: