1. Introduction
In Java, a synchronized map is a thread-safe variant of Map where all the methods are synchronized. This means that multiple threads can modify and access it concurrently without causing concurrent modification exceptions. The Collections class provides a method synchronizedMap to create a synchronized (thread-safe) map backed by the specified map.
2. Program Steps
1. Import necessary libraries.
2. Create a Map.
3. Synchronize the Map using Collections.synchronizedMap().
4. Create multiple threads to modify and access the synchronized map 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 SynchronizedMapExample {
public static void main(String[] args) {
// Step 2: Create a Map
Map<Integer, String> map = new HashMap<>();
// Step 3: Synchronize the Map using Collections.synchronizedMap()
Map<Integer, String> syncMap = Collections.synchronizedMap(map);
// Step 4: Create multiple threads to modify and access the synchronized map concurrently
Thread thread1 = new Thread(() -> {
for (int i = 0; i < 1000; i++) {
syncMap.put(i, "A" + i);
}
});
Thread thread2 = new Thread(() -> {
for (int i = 0; i < 1000; i++) {
syncMap.put(i, "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 map
System.out.println("Size of synchronized map: " + syncMap.size());
}
}
Output:
Size of synchronized map: 1000
4. Step By Step Explanation
Step 1: Import the necessary libraries for handling maps and threads.
Step 2: Create a Map named map.
Step 3: Synchronize the map using Collections.synchronizedMap() method and store it in syncMap.
Step 4: Create two threads thread1 and thread2 to add elements to the syncMap concurrently.
Step 5: Start the threads, wait for them to finish, and then print the size of the syncMap. The output should be 1000, as both threads are adding 1000 elements each to the map with the same keys, demonstrating that syncMap is effectively synchronized, allowing concurrent modifications without throwing any exceptions.