×

CopyOnWriteArrayList in Java

The CopyOnWriteArrayList is used to implement the List Interface. It is the improved version of ArrayList. The operations like add, remove, set, update etc, these operations are done by creating a new copy.

The CopyOnWriteArrayList is consists in the java.util. package.

Syntax for declaring a CopyOnWriteArrayList:

public class CopyOnWriteArrayList<T> extends Object implements List, RandomAccess, Cloneable, Serializable

The Following are some specifications regarding the CopyOnWriteArrayList:

  • CopyOnWriteArrayList generates a cloned copy of the basic ArrayList. For each update operation the both ArrayList and CopyOnWriteArrayList automatically synchronize at a specific point which is handled by the JVM(Java Virtual Machine). There is no specific effect on them if it is a read operation.
  • The CopyOnWriteArrayList is very costly due to creation of the cloned copy for each update operation.
  • The ideal use of the CopyOnWriteArrayList is for the read operation.
  • The insertion in the CopyOnWriteArrayList accepts the null, duplicates and multiple value objects.
  • The remove operation is can not be able to performed by the CopyOnWriteArrayList Iterator. It shows the exception like UnsupportedOperationException.

Constructors used in CopyOnWriteArrayList:

  • CopyOnWriteArrayList():
    It is a default constructor which is used to create a empty ArrayList.
  • CopyOnWriteArrayList(Collection obj):
    The CopyOnWriteArrayList(Collection obj) is a parameterized constructor which create and store the elements present in the specified collection.
  • CopyOnWriteArrayList(Object [] obj):
    TheCopyOnWriteArrayList(Object [] obj) is parameterized constructor which stores the copy of the specified array.

Method Used in CopyOnWriteArrayList:

  • add(E e):
    The add(E e) inserts the specific element e into the list.
  • add(int index, E element):
    The add(int Index, E element) inserts the given element e in the list at a particular index.
  • addAll(Collection <? Extends E> c):
    The addAll(Collection <? Extends E> c) inserts the elements which are included in the particular collection into the end of the list.
  • addAll(int index, Collection <? Extends E> c):
    The addAll(int index, Collection <? Extends E> c) inserts the elememts which are included in the particular collection into the list at a specific position.
  • addAllAbsent(Collection <? Extends E> c):
    The addAllAbsent()(Collection <? Extends E> c) inserts the elements from the particular collection if the list does not contain the elements which are included in that collection.
  • addIfAbsent(E e):
    The addIfAbsent(E e) inserts the element e if that element does not present in the list.
  • contains(Object o):
    The contains(Object o ) validates if the given element present in the list.
    The clone() creates a copy of the list.
  • clear():
    The clear() removes the each and every element present in the list..
  • containsAll(Collection <?> c):
    The contains(Collection <?> c) validates if the list contains the elements present in the particular collection.
  • equals(Object o):
    The equals(Object o) is used for the comparison.
  • get(int index):
    The get(int index) is to retrieve the element from the with the help of the specified index.
  • hashCode():
    The hashCode() gives the hashcode value.
  • indexOf(Object o):
    The element with the first index in the list is returned by the indexOf(Object o) method.
  • isEmpty():
    If the list is empty, the isEmpty() method returns true.
  • remove(Object o):
    The remove(Object o) eliminates the initial element from the list.
  • remove(Int index):
    The remove(int index) eliminates the element from the list with the particular index.
  • removeAll(Collection <?> c):
    The removeAll(Collection <?> c) removes the all the elements present in the list.
  • retainAll(Collection <?> c):
    The retainAll(Collection <?> c) retains the elements with the specified collection.
  • set(int index, E element):
    The set(int index, E element) used to update the element of the list at a particular index.
  • size():
    the size() return the number of the elements present in the list.
  • toArray():
    The toArray() returns the array which containing the same elements of the list.
  • toString():
    The toString() returns the string representation of the List.

Difference between ArrayList and CopyOnWriteArrayList:

They both perform the List interface. However, ArrayList and CopyOnWriteArrayList differ in a number of ways.

  • Every update action at a particular point will automatically synchronize both copies of the ArrayList created by CopyOnWriteArrayList, which is handled by the JVM. As a result, threads that are executing read operations are unaffected. As a result, ArrayList lacks thread safety, whereas CopyOnWriteArrayList does.
  • If another thread attempts to modify an object while one thread is iterating the run-time error is raised. To overcome this error, the CopyOnWriteArrayList can be used.
  • The ArrayList iterator has the ability to remove items while iterating. The CopyOnWriteArrayList Iterator cannot, however, conduct a remove operation while iterating because doing so will cause a run-time exception known as an UnsupportedOperationException.

Example Program:

// Program for the CopyOnWriteArrayList 
import java.util.*;
import java.util.concurrent.CopyOnWriteArrayList;


public class Main extends Thread 
{
static CopyOnWriteArrayList <String> a = new CopyOnWriteArrayList<String>();
public void run()
{
a.add(“H”);
}
public static void main(String args[])
{
a.add(“A”);
a.add(“B”);
a.add(“C”);
Main c = new Main();
c.run();
Thread.sleep(1000);

Iterator itr = a.iterator();
while(itr.hasNext())
{
String s =(String)itr.next();
System.out.println(s);
Thread.sleep(1000);
}
System.out.println(a);
}
}

Output:

A
B
C
H
[A,B,C,H]

Example Program 2:

// program for remove operation in ArrayList while iterating
import java.util.*;
class Main
{
public static void main(String args [])
{
List a = new ArrayList();
a.add(“A”);
a.add(“B”);
a.add(“C”);
Iterator itr = a.iterator();
while(itr.hasNext())
{
String s =(String)itr.next();
if(s.equals(“B”))
{
itr.remove();
}
}
 System.out.println(a);
}
}

Output:

[A, C]

Example Program 3:

// Program for remove operation while iterating in CopyOnWriteArrayLlist.
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.*;
class Copy extends Thread
{
static CopyOnWriteArrayList a = new CopyOnWriteArrayList();
public static void main(String args []) 
{
a.add(“A”);
a.add(“B”);
a.add(“C”);
Iterator itr = a.iterator();
while(itr.next())
{
String s =(String)itr.hasNext();
System.out.println(s);
if(s.equals(“B”))
{
itr.remove();
}
}
System.out.println(a);
} 
}

Output:

A
B
Exception in thread “main”  java.lang.UnsupportedoperationException

Conclusion

The CopyOnWriteArrayList is used to implement the List Interface. It is the improved version of ArrayList. The operations like add, remove, set, update etc, these operations are done by creating a new copy.  CopyOnWriteArrayList generates a cloned copy of the basic ArrayList. For each update operation the both ArrayList and CopyOnWriteArrayList automatically synchronize at a specific point which is handled by the JVM(Java Virtual Machine).


Related Topics

Java Swing Time Picker

Prerequisites In this tutorial, we will learn the time picker in java swing. Before learn time picker, we should learn about java swing. Java Swing Introduction The Java Foundation Classes include Java Swing....

5 minutes read.

Static Array in Java

In this tutorial, we will study static arrays in Java. An array is a data structure that is of great importance in any programming language. It is classified into two...

3 minutes read.

Java Strings

String class is the most used class in Java programming language. The string is the sequence of characters, which is treated as objects in Java. Creating String objects We create String objects...

5 minutes read.

Java String isEmpty() method

Java String isEmpty() method checks whether current String is empty or not. Syntax: public boolean isEmpty() Returns It returns true, if length of String is 0 otherwise false. Java String isEmpty() method example 1    ...

1 minute read.

Collection Interfaces in Java with Examples

In this tutorial, we will discuss collection interfaces in Java with Examples. Introduction The Collection Interface is an individual from the Java Collections Framework. It is a root point of interaction of...

4 minutes read.

Multithreading Program in Java

Multithreading Program in Java: Before discussing multithreading, it is important to discuss threads. Threads are the most fundamental part of a process. A process can have one or more threads....

4 minutes read.

Convert list to array Java

One of the popular collection interfaces for storing an ordered collection is the List. The List interface may contain repeating groups and preserves the insertion order of entries. This article will...

4 minutes read.

How to Convert Binary to Decimal in Java

How to Convert Binary to Decimal in Java There are two methods to convert binary to decimal. Using Integer.parseInt() method Using user-defined logic Using Integer.parseInt() method The parseInt() is a static method of...

2 minutes read.

Java String

Definition A string is a series of characters. Consider an example, "Welcome" is a 7-character string. In Java, String is an unchangeable object. That is, the String is perpetual and cannot be replaced after it is created. This is the tutorial in which you...

4 minutes read.

How to Set Java_home in Linux

To set the Java_home in Linux, we must follow several steps to make us understand it easily.  Java follows the principle called WORA (write once run anywhere). We know that java...

3 minutes read.

Features of Java

The objective of the Java programming language is to provide portability, security, and simplicity. In spite of this, Java has a number of features that makes it a popular language...

5 minutes read.

Java Lock

A lock is indeed a threaded synchronization technique similar to Java's synchronized blocks, however, locking can be more complex. It's not like we can completely get rid of the synchronized...

5 minutes read.

Java Final Keyword

In Java, the last keyword is used to limit the user. The applications of the java final keyword have large range of usage in program development. Last can be: variablemethodclass A final...

3 minutes read.

Java inheritance with Example

Java inheritance Java inheritance is a mechanism in which a child object acquires all the properties and behaviors of a parent object. It helps in reusing the code and establishes...

7 minutes read.

Java Math exp() Method

The exp() method of Math class returns Euler’s number(e) raised to the power of a double value. Syntax: public static double exp(double a) Parameters: The parameter ‘a’ represents the exponent e. Return Value: The exp ()...

2 minutes read.

Java Set to List

In this article, you will be acknowledged about how the process of conversion from Set or HashSet to LinkedList happens and what are the possible ways involved in conversion process. First...

4 minutes read.

Java Integer rotateRight() method

The rotateRight() method of Java Integer class returns the value obtained by rotating the  2’s complement binary representation of the given integer value right by the specified number of bits. Syntax public...

1 minute read.

Java Math sinh() Method

The sinh() method of Java Math class returns the hyperbolic sine of the specified double value. Syntax: public static double sinh(double x) Parameters: The parameter ‘a’ represents the number whose hyperbolic sine is to...

2 minutes read.

Java String contains() method

contains() method returns true only if it contains the given sequence of characters otherwise it returns false. syntax: public boolean contains(CharSequence sequence) parameters: sequence : It is the sequence to be searched. Returns: It returns true...

1 minute read.

How to initialize string array in Java

In this tutorial, we will learn how the string array is initialized in java. The initialization of string array in the java by using the NEW (it creates the object for...

3 minutes read.