In Java, the Collections.synchronizedSet() method creates a thread-safe (synchronized) Set backed by a specified set, allowing safe concurrent access by multiple threads.
- Thread Safety: All operations on the returned set are synchronized.
- Iteration: Iterating over the synchronized set must be done inside a synchronized block to avoid ConcurrentModificationException.
Syntax
public static <T> Set<T> synchronizedSet(Set<T> s)
- Parameters: s is the set to be wrapped in a synchronized (thread-safe) set.
- Return Value: Returns a synchronized view of the specified set.
Example 1: Synchronized Set of Strings
OutputOriginal Set: [1, 2, 3]
Synchronized Set: [1, 2, 3]
Explanation:
- Creates a normal HashSet and wraps it with Collections.synchronizedSet().
- Both original and synchronized sets contain the same elements and are now thread-safe
Example 2: Synchronized Set of Integers
OutputOriginal Set: [100, 200, 300]
Synchronized Set: [100, 200, 300]
Explanation:
- Demonstrates creating a synchronized set with integer values.
- Ensures safe access when multiple threads work with the set.
Example 3: Iterating Over a Synchronized Set
Explanation:
- Iteration over a synchronized set must be done inside a synchronized block.
- Prevents ConcurrentModificationException when accessed by multiple threads.
Example 4: Multi-threaded Access