Collections.synchronizedList()

In Java, Collections.synchronizedList() is a method used to create a thread-safe list. This method is part of the java.util.Collections class and ensures that the list can be accessed by multiple threads without causing concurrency issues. This is particularly useful in multi-threaded environments where multiple threads might be adding, removing, or updating elements in a list simultaneously.

The syntax for creating a synchronized list is as follows:

List<E> synchronizedList = Collections.synchronizedList(new ArrayList<E>());

Here, E represents the type of elements in the list. The method wraps the given list with synchronized access.

Let’s consider a scenario where we have a list of five students in a class. Their names are Paani, Mahesh, Datta, Ganesh, and Harsha. We’ll demonstrate how to create a synchronized list, add the students to it, and iterate through it safely.

import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
public class SynchronizedListExample {
    public static void main(String[] args) {
        // Create a normal ArrayList
        List<String> studentList = new ArrayList<>();
        // Add student names to the list
        studentList.add("Paani");
        studentList.add("Mahesh");
        studentList.add("Datta");
        studentList.add("Ganesh");
        studentList.add("Harsha");
        // Create a synchronized list
        List<String> synchronizedStudentList = Collections.synchronizedList(studentList);
         // Adding elements to the synchronized list
        synchronizedStudentList.add("New Student");
        // Iterating over the synchronized list
        // We need to synchronize the block when iterating
        synchronized (synchronizedStudentList) {
            Iterator<String> iterator = synchronizedStudentList.iterator();
            while (iterator.hasNext()) {
                System.out.println(iterator.next());
            }
        }
        // Demonstrating thread-safe addition
        Thread thread1 = new Thread(new Runnable() {
            public void run() {
                synchronizedStudentList.add("Virat");
                System.out.println("Thread1 added a student");
            }
        });

        Thread thread2 = new Thread(new Runnable() {
            public void run() {
                synchronizedStudentList.add("Vihang");
                System.out.println("Thread2 added a student");
            }
        });

        thread1.start();
        thread2.start();

        // Waiting for threads to finish
        try {
            thread1.join();
            thread2.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        // Print final list
        synchronized (synchronizedStudentList) {
            System.out.println("Final student list:");
            for (String student : synchronizedStudentList) {
                System.out.println(student);
            }
        }
    }
}

/*
D:\>javac SynchronizedListExample.java

D:\>java SynchronizedListExample
Paani
Mahesh
Datta
Ganesh
Harsha
New Student
Thread2 added a student
Thread1 added a student
Final student list:
Paani
Mahesh
Datta
Ganesh
Harsha
New Student
Vihang
Virat
*/

Benefits and Considerations

  • Thread Safety: The primary benefit of using Collections.synchronizedList() is to ensure thread safety when multiple threads are accessing and modifying the list.
  • Simplicity: It provides a simple way to make an existing list thread-safe without having to implement complex synchronization mechanisms.
  • Performance: While synchronizedList ensures thread safety, it can be less performant compared to concurrent collections like CopyOnWriteArrayList for certain use cases, as it locks the entire list on each operation.

Using Collections.synchronizedList() is a straightforward way to handle concurrent modifications to a list in multi-threaded applications. This method ensures that all access to the list is properly synchronized, thus preventing potential concurrency issues.

Scroll to Top