Monday, August 13, 2018

Learn CopyOnWriteArrayList tutorials with examples in java

CopyOnWriteArrayList introduction

CopyOnWriteArrayList is a class in java.util.Concurrent package. This was introduced in Java 5 as part of java concurrency API changes. This is used in multithreaded safe applications. This is a concurrent version of ArrayList.

Why CopyOnWriteArrayList introduced? 

ArrayList is list implementation in java collections ArrayList is not threaded safe and can not be used multi-threaded applications. see the below example Created ArrayList object. Iteration of each element is traversing using Iterate method.
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class ArrayListDemo {
 public static void main(String args[]) {
  List names = new ArrayList<>();
  names.add("one");
  names.add("two");
  names.add("three");
  names.add("four");
  Iterator it = names.iterator();
  while (it.hasNext()) {
   String value = it.next();
   System.out.println(value);
   if (value.equals("three")) {
    names.remove("four");
    names.add("five");
    names.add("four");
   }
  }
  System.out.println(names.size());

 }
}
During iteration, when an element is removed during iterator(), iterator.next() methods throws ConcurrentModifiedException

one
two
three
Exception in thread "main" java.util.ConcurrentModificationException
 at java.util.ArrayList$Itr.checkForComodification(Unknown Source)
 at java.util.ArrayList$Itr.next(Unknown Source)
 at ArrayListDemo.main(ArrayListDemo.java:14)
ArrayList is fail fast, which means if the list is added or removed if any thread is doing iteration, next() method throws ConcurrentModifiedException ArrayList will not work in multithreaded applications as expected.

How CopyOnWriteArrayList object works? 

CopyOnWriteArrayList in multithreaded application is a same or similar class like ArrayList in applications When iterator() called for the first time on this list, It creates a snapshot copy of the list. It will create a cloned version of array list for every modify(add, set remove) operation, and synchronization will be done by JVM. Performance wise is costly as it creates duplicate copy for every modifies operation.

Example

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

public class ListDemo {
 public static void main(String args[]) {
  List myList = new CopyOnWriteArrayList();
  myList.add("ten");
  myList.add("nine");
  myList.add("eight");
  myList.add("seven");
  myList.add("six");
  Iterator it = myList.iterator();
  while (it.hasNext()) {
   String element = it.next();
   System.out.println(element);
   if (element.equals("eight")) {
    myList.remove("seven");
    myList.add("five");
    myList.add("four");
   }
  }
  System.out.println(myList.size());

 }
}

Advantages 

  • Safely iteration of a list when list modified/updated by other thread
  • It is best for a Read operation 
  • suitable for few modifications and many read operations

Disadvantages 

This will be costly if you are doing frequently adding elements

Fix for ConcurrentModifiedException in Multithreaded Applications 

  • Using the Synchronized block to have a lock during iteration
  • Use CopyOnWriteArrayList to avoid this exception

Difference between ArrayList and CopyOnWriteArrayList.

We will see the difference between this list
ArrayList CopyOnWriteArrayList
This class not synchronized Synchronized for thread safety operations
Performance is good performance is less as there is duplicate copy need to be created for every modifies operation during iteration
It throws ConcurrentModifiedException when thread modifies the list during iteration This will never throw an error in multi-thread applications
Iterator on this list is fail-fast Iterator on this list is fail safe
This was introduced in Java 1.2 version This was introduced in Java 1.5 version
This was Used in Multi-thread applications for concurrent Usage This was not stable for multi-thread applications
This is defined in java.util package Defined in java.util.concurrent package
CopyOnWriteArraySet This is useful for set for multi-threaded applications. We will discuss in future posts if you like this post, Please share it in facebook/twitter.

Related article


EmoticonEmoticon