CopyOnWriteArrayList in Java is a thread-safe variant of ArrayList that allows concurrent access for reading while maintaining thread safety for modifications. It achieves this by creating a fresh copy of the underlying array whenever an element is added, modified, or removed, hence the name “copy-on-write.” This makes it suitable for scenarios where reads are more frequent than writes and thread safety is crucial.
The syntax for creating a CopyOnWriteArrayList is similar to creating any other ArrayList:
CopyOnWriteArrayList<E> list = new CopyOnWriteArrayList<>();
Here, E represents the type of elements stored in the list.Code language: PHP (php)import java.util.concurrent.CopyOnWriteArrayList;
public class CopyOnWriteArrayListExample {
public static void main(String[] args) {
// Create a CopyOnWriteArrayList to store student names
CopyOnWriteArrayList<String> studentList = new CopyOnWriteArrayList<>();
// Adding student names to the list
studentList.add("Paani");
studentList.add("Mahesh");
studentList.add("Datta");
studentList.add("Ganesh");
studentList.add("Harsha");
// Display all student names
System.out.println("Student List:");
for (String student : studentList) {
System.out.println(student);
}
// Modify the list concurrently using a separate thread
Thread modifierThread = new Thread(() -> {
// Adding a new student name
studentList.add("New Student");
// Removing a student name
studentList.remove("Harsha");
});
// Start the modifier thread
modifierThread.start();
// Wait for the modifier thread to finish
try {
modifierThread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
// Display updated student list
System.out.println("\nUpdated Student List:");
for (String student : studentList) {
System.out.println(student);
}
}
}
/*
D:\>javac CopyOnWriteArrayListExample.java
D:\>java CopyOnWriteArrayListExample
Student List:
Paani
Mahesh
Datta
Ganesh
Harsha
Updated Student List:
Paani
Mahesh
Datta
Ganesh
New Student
*/
CopyOnWriteArrayList provides a convenient way to manage thread-safe lists in Java applications where concurrency is a concern. It balances between thread safety, predictable iteration behavior, and performance characteristics suitable for specific use cases with high read-to-write ratios and moderate list sizes.
