Java CopyOnWriteArrayList Real-Time Example

In this source code example, you will learn how to use the CopyOnWriteArrayList class in real-time Java projects.

Real-World Example: Student Management with CopyOnWriteArrayList

Imagine you're managing student records, and you need a system that allows multiple threads to safely iterate through student data while also supporting occasional modifications.

In this real-world example, we utilize the CopyOnWriteArrayList to manage student records and safely handle modifications even during iterations, ensuring thread safety.

import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

class Student {
    private String name;
    private int rollNo;

    public Student(String name, int rollNo) {
        this.name = name;
        this.rollNo = rollNo;
    }

    @Override
    public String toString() {
        return "Roll No: " + rollNo + ", Name: " + name;
    }
}

public class StudentManagement {
    public static void main(String[] args) {
        // 1. Initialization
        List<Student> studentList = new CopyOnWriteArrayList<>();
        System.out.println("Initialized student records: " + studentList);

        // 2. Adding students
        studentList.add(new Student("John Doe", 101));
        studentList.add(new Student("Jane Smith", 102));
        studentList.add(new Student("Sam Brown", 103));
        System.out.println("After adding students: " + studentList);

        // 3. Iterate and add new student during iteration
        for (Student student : studentList) {
            System.out.println(student);
            if (student.toString().contains("Jane Smith")) {
                studentList.add(new Student("Emma White", 104));
            }
        }

        System.out.println("After adding student during iteration: " + studentList);
    }
}

Output:

Initialized student records: []
After adding students: [Roll No: 101, Name: John Doe, Roll No: 102, Name: Jane Smith, Roll No: 103, Name: Sam Brown]
Roll No: 101, Name: John Doe
Roll No: 102, Name: Jane Smith
Roll No: 103, Name: Sam Brown
After adding student during iteration: [Roll No: 101, Name: John Doe, Roll No: 102, Name: Jane Smith, Roll No: 103, Name: Sam Brown, Roll No: 104, Name: Emma White]

Explanation:

1. An empty CopyOnWriteArrayList of type Student is initialized to store student records.

2. Students are added to the list using the add method.

3. As we iterate through the student records, we add a new student named "Emma White" when we encounter "Jane Smith".

4. The special feature of CopyOnWriteArrayList is highlighted here: it allows adding elements during iteration without throwing a ConcurrentModificationException.


Comments