Java CopyOnWriteArraySet Real-Time Example

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

Real-World Use Case: Online Classroom Students Registration using CopyOnWriteArraySet

import java.util.Set;
import java.util.concurrent.CopyOnWriteArraySet;

class Student {
    private String name;
    private int studentId;

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

    @Override
    public String toString() {
        return "ID: " + studentId + ", Name: " + name;
    }
}

public class OnlineClassroom {
    public static void main(String[] args) {
        // 1. Initialization
        Set<Student> registeredStudents = new CopyOnWriteArraySet<>();
        System.out.println("Initial registered students: " + registeredStudents);

        // 2. Registering students
        registeredStudents.add(new Student("Amit Sharma", 101));
        registeredStudents.add(new Student("Priya Malhotra", 102));
        registeredStudents.add(new Student("Rahul Joshi", 103));
        System.out.println("After registration: " + registeredStudents);

        // 3. Iterating and registering a student during iteration
        for (Student student : registeredStudents) {
            System.out.println(student);
            if (student.toString().contains("Priya Malhotra")) {
                registeredStudents.add(new Student("Deepika Gupta", 104));
            }
        }

        System.out.println("After registering a student during iteration: " + registeredStudents);
    }
}

Output:

Initial registered students: []
After registration: [ID: 101, Name: Amit Sharma, ID: 102, Name: Priya Malhotra, ID: 103, Name: Rahul Joshi]
ID: 101, Name: Amit Sharma
ID: 102, Name: Priya Malhotra
ID: 103, Name: Rahul Joshi
After registering a student during iteration: [ID: 104, Name: Deepika Gupta, ID: 101, Name: Amit Sharma, ID: 102, Name: Priya Malhotra, ID: 103, Name: Rahul Joshi]

Explanation:

1. An empty CopyOnWriteArraySet of type Student is initialized to keep track of registered students.

2. Students are added to the set using the add method. This ensures that duplicate students (in terms of memory address) won't get registered again.

3. As we iterate through the registered students, we add a new student named "Deepika Gupta" when we encounter "Priya Malhotra".

4. The special feature of CopyOnWriteArraySet is shown here: it allows adding elements during iteration without ConcurrentModificationException.


Comments