Getting Synchronized Set from Java TreeSet
In java.util.Collections class, synchronizedSet() method is used to return a synchronized (thread-safe) set backed by the specified set. This method takes the TreeSet as a parameter. To guarantee serial access, it is critical that all access to the backing set is accomplished through the returned set. We have Java TreeSet, our task is to get a synchronized set from it. For this, use synchronizedSet method of the Collections class.
Input : HashSet = [3, 4, 5] Output: synchronizedSet = [3, 4, 5] Input : HashSet = ['A', 'B', 'C'] Output: synchronizedSet = ['A', 'B', 'C']
public static <T> Set<T> synchronizedSet(Set<T> s)
Parameters: TreeSet as a parameter to be “wrapped” in a synchronized set.
Synchronized view of the specified set.
- Create a TreeSet.
- Add some elements in the TreeSet.
- Create a Set variable and assign it with the Collections.synchronizedSet() method.
- Print the new synchronized Set.
Below is the implementation of the above approach:
TreeSet : [38, 48, 49, 59] SynchronizedSet : [38, 48, 49, 59]