Collections.synchronizedSet and synchronizedMap
You'll learn how to wrap Set and Map implementations in thread-safe synchronized wrappers using the Collections utility class.
The Core Idea
Just as you learned with Collections.synchronizedList, you can create thread-safe versions of Set and Map collections. The Collections utility class provides synchronizedSet() and synchronizedMap() methods that wrap your existing collections in a synchronized layer, making all operations thread-safe by synchronizing on the wrapper object.
Think of it like putting a security guard at the entrance of a building. Only one person (thread) can pass through the door at a time, ensuring nobody bumps into each other inside.
How It Works
When you pass a Set or Map to these methods, Collections returns a wrapper that synchronizes all method calls:
Set<String> regularSet = new HashSet<>();
Set<String> threadSafeSet = Collections.synchronizedSet(regularSet);
Map<String, Integer> regularMap = new HashMap<>();
Map<String, Integer> threadSafeMap = Collections.synchronizedMap(regularMap);
Now threadSafeSet and threadSafeMap are safe to use across multiple threads. All their methods (add, remove, get, put, etc.) are automatically synchronized.
Important: Manual Synchronization for Iteration
Just like with synchronizedList, you must manually synchronize when iterating:
synchronized(threadSafeSet) {
for (String item : threadSafeSet) {
// process item
}
}
synchronized(threadSafeMap) {
for (Map.Entry<String, Integer> entry : threadSafeMap.entrySet()) {
// process entry
}
}
This prevents other threads from modifying the collection while you're iterating through it.
Key Takeaway: Use Collections.synchronizedSet() and Collections.synchronizedMap() to create thread-safe wrappers around Set and Map implementations, but always manually synchronize around iteration blocks to avoid ConcurrentModificationException.