Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
CopyOnWriteArrayList
3.
Constructors
4.
Methods
5.
Basic operations
6.
FAQs
7.
Key Takeaways
Last Updated: Mar 27, 2024

CopyOnWriteArrayList

Author Yashesvinee V
0 upvote
Create a resume that lands you SDE interviews at MAANG
Speaker
Anubhav Sinha
SDE-2 @
12 Jun, 2024 @ 01:30 PM

Introduction

An ArrayList is one of the basic implementations of the List interface and is a part of the Java Collections Framework. An iterator is used to traverse the ArrayList elements. The ArrayList iterator is fail-fast by design, which means that once the iterator is created and then modified in terms of size, ConcurrentModificationException is thrown. The CopyOnWriteArrayList is a thread-safe version of the ArrayList and helps prevent this exception.

Also read, Duck Number in Java and Hashcode Method in Java

CopyOnWriteArrayList

  • The CopyOnWriteArrayList is thread-safe and can be used in a multithreaded environment without any problems. It is achieved without the need for synchronisation.
     
  • The JVM clones the ArrayList when modifications that alter its size are performed. A new copy of the list is created and then modified for every write operation.
     
  • Multiple threads can read data from a CopyOnWriteArrayList simultaneously. Data is written by one thread at a time.
     
  • It can contain null values and duplicate elements.
     
  • CopyOnWriteArrayList iterators can not perform remove, add and set operations as they result in a Run-time exception known as UnsupportedOperationException.
     

Declaration:

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

Also see,  Swap Function in Java

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Constructors


 

Methods

 

Basic operations

  • Add/Update elements
     
import java.util.*;
import java.util.concurrent.*;

public class Main {
    public static void main(String[] args) {
        CopyOnWriteArrayList<Integer> numbers= new CopyOnWriteArrayList<>();

        // Using the add() method
        numbers.add(2);
        numbers.add(4);
        
        numbers.addIfAbsent(6);

        System.out.println("list: " + numbers);

        CopyOnWriteArrayList alphanum = new CopyOnWriteArrayList();
        alphanum.add("a");
        alphanum.add("b");

        alphanum.addAll(numbers);
        System.out.println("New list: " + alphanum);
        alphanum.set(2,"c");
        System.out.println("Final list after updation:" + alphanum);
    }
}

 

Output:

list: [2, 4, 6]
New list: [a, b, 2, 4, 6]
Final list after updation:[a, b, c, 4, 6]


Try it on Java Online Compiler.
 

  • Access elements
     
import java.util.*;
import java.util.concurrent.*;

public class Main {
    public static void main(String[] args) {
        CopyOnWriteArrayList<Integer> numbers= new CopyOnWriteArrayList<>();

        // Using the add() method
        numbers.add(2);
        numbers.add(4);
        numbers.add(6);
        numbers.addIfAbsent(8);

        System.out.println("list: " + numbers);

        System.out.println("Element at index 2: " + numbers.get(2));
        
        System.out.println("list after updation:");
        numbers.forEach((e) -> {
            e = e * 10;
          System.out.print(e + " ");
        });
      System.out.println("\nSublist 1-3:  " + numbers.subList(0,3));
    }
}


Output:

list: [2, 4, 6, 8]
Element at index 2: 6
list after updation:
20 40 60 80 
Sublist 1-3:  [2, 4, 6]

 

  • Remove elements
     
import java.util.*;
import java.util.concurrent.*;

public class Main {
    public static void main(String[] args) {
        CopyOnWriteArrayList<Integer> numbers= new CopyOnWriteArrayList<>();

        // Using the add() method
        numbers.add(2);
        numbers.add(4);
        numbers.add(6);
        numbers.addIfAbsent(8);

        System.out.println("list: " + numbers);
        
        System.out.println("Removing Element at index 3..  ");
        numbers.remove(3);
        
        System.out.println("Removing Elements less than 5..  ");
        numbers.removeIf(e -> e<5);
        
        System.out.println("Final list :  " + numbers);
        
    }
}

 

Output:

list: [2, 4, 6, 8]
Removing Element at index 3..  
Removing Elements less than 5..  
Final list :  [6]

 

Check out this problem - Duplicate Subtree In Binary Tree

FAQs

  1. What is the difference between Synchronized ArrayList and CopyOnWriteArrayList?

    Synchronised Arraylist iterators are fail-fast and must be contained within the synchronised block. CopyOnWriteArrayList iterators are fail-safe and can be used outside the synchronised block. The entire ArrayList is blocked for both read and write operations in a Synchronised ArrayList. The ArrayList is blocked only for write operations in a CopyOnWriteArrayList.
     
  2. What is the advantage of using CopyOnWriteArrayList?

    Making a fresh copy of an array consumes both time and memory overhead. To avoid this, developers often resort to using a synchronised ArrayList instead. However, every time you iterate across the contents of the collection, there is a need to synchronise all operations, including read and write, to ensure consistency. The CopyOnWriteArrayList easily solves this problem.

Key Takeaways

This article extensively discusses CopyOnWriteArrayList. We hope that this blog has helped you enhance your knowledge about the different methods and ways of implementing the CopyOnWriteArrayList class in Java. If you would like to learn more, check out our articles on Data Structures in JavaMultithreading in Java and lists vs Arrays.

Recommended Articles::

Recommended problems -

 

Explore our Coding Ninjas Library and upvote our blog to help other ninjas grow.  Happy Coding!

Previous article
Abstract Sequential List
Next article
Custom ArrayList
Live masterclass