×

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 Integer remainder Unsigned() method

The remainderUnsigned() method of Java Integer class returns the unsigned remainder by dividing the first and second argument. Syntax public static int remainderUnsigned(int dividend, int divisor)  Parameters The ‘dividend’ and ‘divisor’ represents the value...

1 minute read.

How to Calculate Time Difference Between Two Dates in Java?

Date is being used extensively in Java to calculate date differences. While constructing an application, the date of joining an organisation, admission date, appointment date, and others might be included....

4 minutes read.

Java Boolean logicalOr() Method

The logicalOr() method of Java Boolean class returns the result of implementing logical OR operation on the specified Boolean operands. Syntax: public static boolean logicalOr (boolean a, boolean b) Parameters: The parameters ‘a’ and...

2 minutes read.

Number Pattern Programs in Java

Number Pattern Programs in Java: Number pattern programs are part of pattern programs. In the previous section, we have learned the approach to print the pattern program in Java. To...

6 minutes read.

Convert List to String in Java

We occasionally need to create a string from a list of characters. Since a string is only a collection of characters, a character array can be converted into a string....

6 minutes read.

Balanced Parentheses in Java

One of the frequent programming issues, commonly referred to as the Balanced brackets issue, is the problem with the balanced parenthesis. Interviewers frequently provide this task, in which we must...

5 minutes read.

How to take Array Input in Java

In this tutorial, we will learn about how to take array input in Java. So, before taking inputs let us know what an array is first. Array: An array is a collection...

10 minutes read.

Radix Sort in Java

Radix Sort in Java Radix sort in Java uses the digits of the numbers given in the sorted array to sort the numbers. The radix sort uses the place value of...

5 minutes read.

Traverse through HashMap in Java

In this tutorial, we will discuss traversing through HashMap in Java Introduction: HashMap<Key, Value> is a part of the java collection implemented from the java 1.2 version. HashMap is written as HashMap<K,...

4 minutes read.

Segment Tree in Java

Binary trees can address a variety of issues; however, the Segment Tree is more efficient in terms of time complexity. The segment tree in Java is represented using an array. Native...

4 minutes read.

Java Enhanced For Loop (For-each Loop)

JAVA ENHANCED FOR LOOP The enhanced for loop is also called the for-each loop and has some advantages over the regular for loop. A for-each loop is designed to cycle through...

4 minutes read.

Java String Matches vs Contains

String Matches in Java The matches() function and its variations are used to determine whether or not a provided text matches a regular expression. The functioning as well as output of...

3 minutes read.

Session Tracking in Java

When a series of requests from the same User (i.e., requests coming from the same browser) occurs over an extended period of time, servlets employ a mechanism known as session...

3 minutes read.

Read JSON file in Java

 To know about reading a JSON file in Java first we must know about the JSON file. JSON: JSON is “JavaScript Object Notation”. The JSON is the simple format for storing and...

3 minutes read.

Method and Block Synchronization in Java

The Synchronization is performed in multi-threading concept. The multi-threading is a concept of parallel running of a program for the execution. In the multi-threading concept, the threads are run by...

3 minutes read.

Sorting a String in Java

Sorting a String in Java Sorting is a process of arranging available data objects in a meaningful format that is ascending or descending order. Sorting a string or array of String...

4 minutes read.

Why we use static in Java

Many reserved keywords in Java cannot be used as variable names or identifiers. Java uses static keywords frequently because of its effective memory management system. In most cases, you must...

3 minutes read.

Java Viva Questions and Answers

Question: Explain Java programming language. Answer: It is a high-level programming language. This programming language is based on the principles of object-oriented programming. Large-scale applications can be developed by using this...

16 minutes read.

String Programs in Java

String Programs in Java: In Java, a String is an immutable object that represents a sequence of characters. For example, “Tutorial” is a string that consists of 8 characters: ‘T’,...

10 minutes read.

Java String toCharArray() method

Java String toCharArray() method converts current String into character array. Syntax: public char[] toCharArray() Returns: It returns a character array Java String toCharArray() method example 1 import java.util.Arrays; public class JavaStringToCharArrayEx1 {           public static...

2 minutes read.