CopyOnWriteArrayList

CopyOnWriteArrayList is a thread-safe variant of ArrayList provided by the Java Collections Framework. It belongs to the java.util.concurrent package and implements the List interface. This class is specifically designed to handle concurrent read and write operations efficiently, making it ideal for situations where there are frequent read operations and relatively fewer write operations.

Key Features:

  • Thread Safety: The primary feature of CopyOnWriteArrayList is its thread safety. It achieves this by making a copy of the underlying array whenever a write operation occurs (e.g., adding, removing, or modifying elements). This ensures that readers will never see inconsistent data.
  • Performance: The list performs well in read-heavy scenarios. The cost of write operations (such as adding or removing elements) is high because they involve copying the entire array. However, read operations like get(), size(), and iteration (forEach) are much faster compared to other synchronized collections.
  • Copying on Write: Whenever a modification occurs, such as an insertion, deletion, or update, the list creates a new copy of the underlying array and modifies the new array. This allows existing threads that are iterating over the list to continue without being interrupted by the modification.

When to Use:

  • Read-Heavy Workloads: Use CopyOnWriteArrayList when your application is primarily reading from the list, and writes (modifications) happen infrequently.
  • Concurrent Iteration: It is particularly useful when you need to iterate over a list concurrently while modifying it in other parts of the program.

Program

This program demonstrates the use of CopyOnWriteArrayList by adding, removing, and modifying elements while iterating over the list. Ensure that modifications during iteration (e.g., adding an element) do not throw a ConcurrentModificationException. Additionally, verify the list’s contents after modifications and check if a specific element exists in the list.

import java.util.Iterator;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
public class CopyOnWriteArrayListDemo {
    public static void main(String[] args) {
        // Creating a CopyOnWriteArrayList
        List<String> copyOnWriteArrayList = new CopyOnWriteArrayList<>();
        // Adding elements to the list
        copyOnWriteArrayList.add("Ganga");
        copyOnWriteArrayList.add("Godhavari");
        copyOnWriteArrayList.add("Krishna");
        // Iterating over the list
        Iterator<String> iterator = copyOnWriteArrayList.iterator();
        while (iterator.hasNext()) {
            String fruit = iterator.next();
            System.out.println(fruit);
            // Modifying the list while iterating does not throw ConcurrentModificationException
            if (fruit.equals("Ganga")) {
                copyOnWriteArrayList.add("Narmada");
            }
        }
        System.out.println("After modification:");
        copyOnWriteArrayList.forEach(System.out::println);
        // Removing an element from the list
        copyOnWriteArrayList.remove("Godhavari");
        // Checking if the list contains an element
        System.out.println("Contains Apple: " + copyOnWriteArrayList.contains("Narmada"));
    }
}
/*
C:\>javac CopyOnWriteArrayListDemo.java

C:\>java CopyOnWriteArrayListDemo
Ganga
Godhavari
Krishna
After modification:
Ganga
Godhavari
Krishna
Narmada
Contains Apple: true
*/

CopyOnWriteArrayList is a highly useful, thread-safe collection in Java, designed for scenarios where read operations are frequent, and write operations are infrequent. It ensures safe iteration even when the list is modified concurrently, by creating a new copy of the underlying array on every modification. However, its performance may degrade with frequent write operations due to the overhead of copying the array, making it most suitable for applications with a read-heavy workload.

Scroll to Top