Introduction to CopyOnWriteArrayList Class in Java
The CopyOnWriteArrayList
class is a member of Java Collections Framework. It is a thread safe variant of ArrayList Class found in java.util.concurrent
package. This class implements the List interface along with the other interface like RandomAccess
, Cloneable, Serializable. Here, all the mutative operations like add, set, etc are implemented by making a fresh copy of underlying array. This class allows all type of elements including null.
Normally, this is comparatively expensive but can be more efficient than alternatives when traversal operations greatly outnumber mutations. Also, when synchronizing traversals is not an option, but you still want to prevent interference between concurrent threads.
Here, the iterator will not reflect additions, removals, or changes to the list since the iterator was created. Element-changing operations on iterators themselves (remove, set, and add) are not supported. These methods throw UnsupportedOperationException
.
Constructor of CopyOnWriteArrayList Class in Java
There are two ways in which constructors are created for this class in Java.
Empty constructor
When we create an object like as shown below, this empty constructor will be called. Hence, the statement below creates an empty list.
Example :
CopyOnWriteArrayList l = new CopyOnWriteArrayList();
Constructor with Collection as a parameter
This type of constructor creates a list containing the elements of the given collection, in the order they are returned by the collection's iterator. However, it will throw a NullPointerException
if the specified collection is null.
Example :
CopyOnWriteArrayList c = new CopyOnWriteArrayList(Collection<> c)
Constructor with Array as a parameter
This type of constructor creates a list holding a copy of the given array. However, it will throw a NullPointerException
if the specified array is null.
Example :
CopyOnWriteArrayList c = new CopyOnWriteArrayList(E[] c)
Methods of CopyOnWriteArrayList Class in Java
The table below lists all the methods of CopyOnWriteArrayList in Java.
Method | Description |
---|---|
add(E e) | Appends the given element to the end of this list. |
add(int index, E element) | Inserts the given element at the index position in this list. |
addAll(Collection c) | Appends all of the elements in the given collection to the end of this list, in the order that they are returned by the collection’s iterator. |
addAll(int index, Collection c) | Inserts all of the elements in the given collection into this list, starting at the index position. |
addAllAbsent(Collection c) | Appends all of the elements in the given collection that are not already contained in this list, to the end of this list, in the order that they are returned by the given collection’s iterator. |
addIfAbsent(E e) | Appends the element, if not present. |
clear() | Removes all of the elements from this list. |
clone() | Returns a shallow copy of this list. |
contains(Object o) | Returns true if this list contains the given element. |
containsAll(Collection c) | Returns true if this list contains all of the elements of the given collection. |
equals(Object o) | Compares the given object with this list for equality. |
get(int index) | Returns the element at the given position in this list. |
hashCode() | Returns the hash code value for this list. |
indexOf(E e, int index) | Returns the index of the first occurrence of the given element in this list, searching forwards from the index, or returns -1 if the element is not found. |
indexOf(Object o) | Returns the index of the first occurrence of the given element in this list, or -1 if this list does not contain the element. |
isEmpty() | Returns true if this list contains no elements. |
iterator() | Returns an iterator over the elements in this list in the proper sequence. |
lastIndexOf(E e, int index) | Returns the index of the last occurrence of the given element in this list, searching backward from the index, or returns -1 if the element is not found. |
lastIndexOf(Object o) | Returns the index of the last occurrence of the given element in this list, or -1 if this list does not contain the element. |
listIterator() | Returns a list iterator over the elements in this list (in proper sequence). |
listIterator(int index) | Returns a list iterator over the elements in this list (in proper sequence), starting at the given position in the list. |
remove(int index) | Removes the element at the given position in this list. |
remove(Object o) | Removes the first occurrence of the given element from this list, if it is present. |
removeAll(Collection c) | Removes from this list all of its elements that are contained in the given collection. |
retainAll(Collection c) | Retains only the elements in this list that are contained in the given collection. |
set(int index, E element) | Replaces the element at the given position in this list with the given element. |
size() | Returns the number of elements in this list. |
subList(int fromIndex, int toIndex) | Returns a view of the portion of this list between fromIndex, inclusive, and toIndex, exclusive. |
toArray() | Returns an array containing all of the elements in this list in proper sequence (from first to the last element). |
toArray(T[] a) | Returns an array containing all of the elements in this list in proper sequence (from first to the last element); the runtime type of the returned array is that of the given array. |
toString() | Returns a string representation of this list. |
Operations on CopyOnWriteArrayList in Java
The basic operations that can be performed using CopyOnWriteArrayList
in Java are as listed below.
- Insertion Operation
- Deletion Operation
- Update Operation
Insertion Operation
An element can be added to an existing CopyOnWriteArrayList
list using methods like add, addAll
, addAllAbsent
, addIfAbsent
as shown in the example below.
import java.util.*;
import java.util.concurrent.CopyOnWriteArrayList;
public class Main extends Thread {
static CopyOnWriteArrayList l
= new CopyOnWriteArrayList();
public void run() {
// Child thread adds new color to the list
l.add("Red");
l.addIfAbsent("Pink");
l.addIfAbsent("Brown");
}
public static void main(String[] args)
throws InterruptedException {
List c = new ArrayList();
c.add("Gray");
c.add("Black");
c.add("Brown");
l.add("Green");
l.add("Orange");
l.add("White");
l.addAll(c);
// Creating a child thread that modifies the list
Main m = new Main();
m.run();
Thread.sleep(1000);
// Iterating on list
Iterator i = l.iterator();
while (i.hasNext()) {
String s = (String) i.next();
System.out.println(s);
Thread.sleep(1000);
}
System.out.println(l);
}
}
Output
Green
Orange
White
Gray
Black
Brown
Red
Pink
[Green, Orange, White, Gray, Black, Brown, Red, Pink]
Deletion Operation
An element can be deleted from an existing CopyOnWriteArrayList list using methods like remove, removeAll, as shown in the example below.
import java.util.*;
import java.util.concurrent.CopyOnWriteArrayList;
public class Main extends Thread {
static CopyOnWriteArrayList l
= new CopyOnWriteArrayList(Arrays.asList("Red", "Green", "Orange", "White", "Blue"));
public void run() {
// Child thread adds new color to the list
l.add("Red");
l.addIfAbsent("Pink");
l.addIfAbsent("Brown");
}
public static void main(String[] args)
throws InterruptedException {
List c = new ArrayList(Arrays.asList("Brown", "White"));
System.out.println("List is " + l);
System.out.println("Removing Red " + l.remove("Red"));
System.out.println("Removing all of list c " + l.removeAll(c));
// Creating a child thread that modifies the list
Main m = new Main();
m.run();
System.out.println("After Thread List is " + l);
// Iterating on list
Iterator i = l.iterator();
while (i.hasNext()) {
String s = (String) i.next();
System.out.println(s);
Thread.sleep(1000);
}
System.out.println(l);
}
}
Output
List is [Red, Green, Orange, White, Blue]
Removing Red true
Removing all of list c true
After Thread List is [Green, Orange, Blue, Red, Pink, Brown]
Green
Orange
Blue
Red
Pink
Brown
[Green, Orange, Blue, Red, Pink, Brown]
Update Operation
An element can be updated in an existing CopyOnWriteArrayList
list using set method as shown in the example below.
import java.util.*;
import java.util.concurrent.CopyOnWriteArrayList;
public class Main extends Thread {
static CopyOnWriteArrayList l
= new CopyOnWriteArrayList(Arrays.asList("Red", "Green", "Orange", "White", "Blue"));
public void run() {
// Child thread updates the new color at index 3
l.set(3, "Black");
}
public static void main(String[] args)
throws InterruptedException {
System.out.println("List is " + l);
// Creating a child thread that modifies the list
Main m = new Main();
m.run();
System.out.println("After Thread List is " + l);
}
}
Output
List is [Red, Green, Orange, White, Blue] After Thread List is [Red, Green, Orange, Black, Blue]
Summary
The knowledge of CopyOnWriteArrayList
in Java is very useful while working on real time multi thread applications. In many situations, we will need to have a list where multiple threads are performing operations on the list. In this tutorial, we covered constructors and methods of CopyOnWriteArrayList
class along with the important operations that can be performed using the built-in methods of CopyOnWriteArrayList
class with the example. As per the requirement of an application, we can choose an appropriate methods. We learned in detail about this with an example. All in all, this tutorial, covers everything that you need to know in order to have a clear view on CopyOnWriteArrayList
in Java.
References