The synchronizedList()
method in Java is a utility method provided by the java.util.Collections
class. It returns a synchronized (thread-safe) list backed by the specified list. This method is useful when you need to ensure that a list is thread-safe in a concurrent environment.
Table of Contents
- Introduction
synchronizedList()
Method Syntax- Examples
- Basic Usage of
synchronizedList()
- Using
synchronizedList()
with Custom Classes
- Basic Usage of
- Real-World Use Case
- Conclusion
Introduction
The Collections.synchronizedList()
method provides a way to wrap a given list with synchronized access, ensuring that only one thread can access the list at a time. This is crucial in concurrent applications where multiple threads might try to modify the list simultaneously, leading to race conditions or inconsistent data.
The returned list is a synchronized view of the specified list, meaning that all the operations on the list are synchronized using the list’s intrinsic lock. This includes operations such as adding, removing, or iterating over the elements.
synchronizedList() Method Syntax
The syntax for the synchronizedList()
method is as follows:
public static <T> List<T> synchronizedList(List<T> list)
Parameters:
list
: The list to be wrapped in a synchronized view.
Returns:
- A synchronized (thread-safe) list backed by the specified list.
Throws:
NullPointerException
if the specified list is null.
Examples
Basic Usage of synchronizedList()
The following example demonstrates how to use the synchronizedList()
method to create a synchronized view of a list.
Example
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 regular ArrayList
List<String> list = new ArrayList<>();
list.add("Apple");
list.add("Banana");
list.add("Cherry");
// Create a synchronized (thread-safe) list backed by the ArrayList
List<String> synchronizedList = Collections.synchronizedList(list);
// Display the synchronized list
System.out.println("Synchronized List: " + synchronizedList);
// Use synchronized block for iteration to ensure thread safety
synchronized (synchronizedList) {
Iterator<String> iterator = synchronizedList.iterator();
while (iterator.hasNext()) {
System.out.println("Element: " + iterator.next());
}
}
// Adding and removing elements in a synchronized list
synchronized (synchronizedList) {
synchronizedList.add("Date");
synchronizedList.remove("Apple");
}
// Display the modified synchronized list
System.out.println("Modified Synchronized List: " + synchronizedList);
}
}
Output:
Synchronized List: [Apple, Banana, Cherry]
Element: Apple
Element: Banana
Element: Cherry
Modified Synchronized List: [Banana, Cherry, Date]
Using synchronizedList() with Custom Classes
You can also use the synchronizedList()
method with lists containing instances of custom classes.
Example
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
class Student {
String name;
Student(String name) {
this.name = name;
}
@Override
public String toString() {
return name;
}
}
public class CustomSynchronizedListExample {
public static void main(String[] args) {
// Create a list of students
List<Student> students = new ArrayList<>();
students.add(new Student("Amit"));
students.add(new Student("Neha"));
students.add(new Student("Raj"));
// Create a synchronized (thread-safe) list backed by the list of students
List<Student> synchronizedStudents = Collections.synchronizedList(students);
// Display the synchronized student list
System.out.println("Synchronized Student List: " + synchronizedStudents);
// Use synchronized block for iteration to ensure thread safety
synchronized (synchronizedStudents) {
Iterator<Student> iterator = synchronizedStudents.iterator();
while (iterator.hasNext()) {
System.out.println("Student: " + iterator.next());
}
}
// Modifying the synchronized list
synchronized (synchronizedStudents) {
synchronizedStudents.add(new Student("Vikram"));
synchronizedStudents.remove(new Student("Neha"));
}
// Display the modified synchronized student list
System.out.println("Modified Synchronized Student List: " + synchronizedStudents);
}
}
Output:
Synchronized Student List: [Amit, Neha, Raj]
Student: Amit
Student: Neha
Student: Raj
Modified Synchronized Student List: [Amit, Neha, Raj, Vikram]
Explanation:
-
Synchronized View: The
synchronizedList()
method returns a synchronized view of the specified list, ensuring thread-safe access. -
Synchronized Block: When iterating over the synchronized list, a synchronized block is used to avoid concurrent modification exceptions and ensure thread safety.
-
Custom Class: The method works with custom class instances, allowing you to create synchronized lists with user-defined objects.
Real-World Use Case
Thread-Safe Access to a Shared Resource
In real-world applications, the synchronizedList()
method can be used to manage thread-safe access to shared resources, such as a list of tasks in a multi-threaded environment.
Example
Imagine a scenario where you need to manage a shared list of tasks in a concurrent application.
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
class Task {
String description;
Task(String description) {
this.description = description;
}
@Override
public String toString() {
return description;
}
}
public class TaskManager {
private final List<Task> tasks;
public TaskManager() {
// Initialize the task list and wrap it in a synchronized view
this.tasks = Collections.synchronizedList(new ArrayList<>());
}
public void addTask(Task task) {
synchronized (tasks) {
tasks.add(task);
}
}
public void removeTask(Task task) {
synchronized (tasks) {
tasks.remove(task);
}
}
public void displayTasks() {
// Use synchronized block for iteration to ensure thread safety
synchronized (tasks) {
Iterator<Task> iterator = tasks.iterator();
while (iterator.hasNext()) {
System.out.println("Task: " + iterator.next());
}
}
}
public static void main(String[] args) {
TaskManager taskManager = new TaskManager();
// Add tasks to the manager
taskManager.addTask(new Task("Review code"));
taskManager.addTask(new Task("Write tests"));
taskManager.addTask(new Task("Deploy application"));
// Display all tasks
System.out.println("Task List:");
taskManager.displayTasks();
}
}
Output:
Task List:
Task: Review code
Task: Write tests
Task: Deploy application
Explanation:
-
Task Manager: The
TaskManager
class manages a list of tasks, ensuring thread-safe access by wrapping the list in a synchronized view. -
Concurrent Environment: The
synchronizedList()
method is used to synchronize access to the shared list, preventing race conditions and ensuring data consistency.
Conclusion
The Collections.synchronizedList()
method is a powerful utility for creating synchronized (thread-safe) lists in Java. By providing a simple way to wrap lists with synchronized access, it enhances the flexibility and safety of your code in concurrent environments. This method is particularly valuable in scenarios where you need to manage shared resources or ensure thread-safe access to lists, improving the robustness and maintainability of your Java applications.