1. Introduction
In Java, a synchronized list is a thread-safe variant of List in which all the methods are synchronized. This means that multiple threads can modify and access it concurrently without any concurrent modification exceptions. Java provides a utility method Collections.synchronizedList to create a synchronized (thread-safe) list backed by the specified list.
2. Program Steps
1. Import necessary libraries.
2. Create a List.
3. Synchronize the List using Collections.synchronizedList().
4. Create multiple threads to modify and access the synchronized list concurrently.
5. Start the threads and observe that no concurrent modification exception occurs.
3. Code Program
// Step 1: Import necessary libraries
import java.util.*;
class SynchronizedListExample {
public static void main(String[] args) {
// Step 2: Create a List
List<String> list = new ArrayList<>();
// Step 3: Synchronize the List using Collections.synchronizedList()
List<String> syncList = Collections.synchronizedList(list);
// Step 4: Create multiple threads to modify and access the synchronized list concurrently
Thread thread1 = new Thread(() -> {
for (int i = 0; i < 1000; i++) {
syncList.add("A" + i);
}
});
Thread thread2 = new Thread(() -> {
for (int i = 0; i < 1000; i++) {
syncList.add("B" + i);
}
});
// Start the threads
thread1.start();
thread2.start();
// Wait for threads to finish
try {
thread1.join();
thread2.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
// Step 5: Print the synchronized list
System.out.println("Size of synchronized list: " + syncList.size());
}
}
Output:
Size of synchronized list: 2000
4. Step By Step Explanation
Step 1: Import the necessary libraries for handling lists and threads.
Step 2: Create a List named list.
Step 3: Synchronize the list using Collections.synchronizedList() method and store it in syncList.
Step 4: Create two threads thread1 and thread2 to add elements to the syncList concurrently.
Step 5: Start the threads, wait for them to finish, and then print the size of the syncList. The output should be 2000, as both threads are adding 1000 elements each to the list, demonstrating that syncList is effectively synchronized, allowing concurrent modifications without throwing any exceptions.