ConcurrentSkipListSet class and Collections.SynchronizedSet() method in Java
In this post, we will compare and contrast ConcurrentSkipListSet and Collections.SynchronizedSet() in Java that are used to implement a synchronized set in Java.
1. Overview of ConcurrentSkipListSet
ConcurrentSkipListSet is a class that implements the Set and NavigableSet interfaces and uses a concurrent skip list as its underlying data structure to store elements. A concurrent skip list is a probabilistic data structure that consists of multiple linked lists arranged in a hierarchy. The elements in a concurrent skip list are sorted by default in their natural ordering or by a Comparator provided at set creation time, depending on which constructor is used. It offers many benefits:
ConcurrentSkipListSetallows safe execution of insertion, removal, and access operations on set concurrently by multiple threads. It should be preferred over other Set interface implementations when concurrent modification of set by multiple threads is required.ConcurrentSkipListSetdoes not lock the entire set, but only parts of it, allowing parallel access for multiple threads. This means that multiple threads can access the set at the same time without blocking each other, which improves the performance.ConcurrentSkipListSetdoes not allow null elements in the set. This means that we cannot insert null values in aConcurrentSkipListSetwithout throwing an exception.ConcurrentSkipListSetpreserves the order of the elements in the set. This means that we can iterate over the elements in aConcurrentSkipListSetin a sorted order according to their natural ordering or by a providedComparator.ConcurrentSkipListSetprovides additional methods to navigate the set in a sorted order, such asfirst(),last(),lower(),higher(), etc. These methods allow us to access the first or last element in the set, or find an element that is less than or greater than a given element.
Let’s see an example of how to create and use a ConcurrentSkipListSet in Java:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
import java.util.Arrays; import java.util.concurrent.ConcurrentSkipListSet; class Main { public static void main(String[] args) { // Create a ConcurrentSkipListSet object ConcurrentSkipListSet<Integer> set = new ConcurrentSkipListSet<>( Arrays.asList(10, 4, 6, 2, 8)); // Print the set System.out.println("ConcurrentSkipListSet: " + set); // [2, 4, 6, 8, 10] // Remove an element from the set set.remove(6); // Print the updated set System.out.println("ConcurrentSkipListSet: " + set); // [2, 4, 8, 10] // Access the first element in the set System.out.println("First: " + set.first()); // 2 // Access the last element in the set System.out.println("Last: " + set.last()); // 10 // Access an element that is less than 5 System.out.println("Lower than 5: " + set.lower(5)); // 4 // Access an element that is greater than 5 System.out.println("Higher than 5: " + set.higher(5)); // 8 } } |
2. Overview of Collections.SynchronizedSet() method
The Collections.synchronizedSet() is a static method of the Collections class that returns a synchronized or thread-safe set backed by the specified set. This method is used to create a synchronized wrapper around an existing set, such as HashSet, TreeSet, or LinkedHashSet. It offers some benefits over ConcurrentSkipListSet:
SynchronizedSet()locks the entire set, blocking parallel access for multiple threads. This means that only one thread can access the set at a time, which ensures data consistency and prevents concurrency issues.SynchronizedSet()allows null elements in the set, only if the backing set does. This means that we can insert null values in aSynchronizedSet()if the backing set allows it.SynchronizedSet()does not preserve the order of the elements in the set, unless the backing set does. This means that the order of the elements in aSynchronizedSet()depends on the type of the backing set. IfHashSetis used as the backing set, the order of the elements is undefined. IfTreeSetis used as the backing set, the order of the elements is the same as the natural ordering of its elements or that of a provided Comparator. IfLinkedHashSetis used as the backing set, the order of the elements is the same as their insertion order.SynchronizedSet()does not provide any additional methods to navigate the set in a sorted order, unless the backing set does. This means that we cannot access the first or last element in the set, or find an element that is less than or greater than a given element, unless we use aTreeSetas the backing set.
Let’s see an example of how to create and use a SynchronizedSet() in Java:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
import java.util.Arrays; import java.util.Collections; import java.util.HashSet; import java.util.Set; class Main { public static void main(String[] args) { // Create a HashSet object Set<Integer> hashSet = new HashSet<>(Arrays.asList(10, 4, 6, 2, 8)); // Create a SynchronizedSet object backed by hashSet Set<Integer> syncSet = Collections.synchronizedSet(hashSet); // Print the syncSet System.out.println("SynchronizedSet: " + syncSet); // [2, 4, 6, 8, 10] // Remove an element from the syncSet syncSet.remove(6); // Print the updated syncSet System.out.println("SynchronizedSet: " + syncSet); // [2, 4, 8, 10] // Access an element in the syncSet using an iterator synchronized (syncSet) { for (Integer i : syncSet) { System.out.println(i); // 2, 4, … } } } } |
3. Differences between ConcurrentSkipListSet and Collections.SynchronizedSet()
Here are some of the main differences between ConcurrentSkipListSet and Collections.SynchronizedSet() in Java:
ConcurrentSkipListSetis a class that implementsSetandNavigableSetinterfaces, whileSynchronizedSet()is a method ofCollectionsclass that returns aSetinterface.ConcurrentSkipListSetuses a concurrent skip list as its underlying data structure, whileSynchronizedSet()uses any type of set as its underlying data structure.ConcurrentSkipListSetallows parallel access for multiple threads without blocking them, whileSynchronizedSet()blocks parallel access for multiple threads and allows only one thread to access the set at a time.ConcurrentSkipListSetdoes not allow null elements in the set, whileSynchronizedSet()allows null elements in the set depending on the backing set.ConcurrentSkipListSetpreserves the order of the elements in the set according to their natural ordering or by a providedComparator, whileSynchronizedSet()does not preserve the order of the elements in the set unless the backing set does.ConcurrentSkipListSetprovides additional methods to navigate the set in a sorted order, such as first, last, lower, higher, etc., whileSynchronizedSet()does not provide any additional methods to navigate the set in a sorted order unless the backing set does.ConcurrentSkipListSetiterator is weakly consistent, which never throwsConcurrentModificationExceptioneven if the set is modified after the construction of the iterator. On the contrary,SynchronizedSet()does not guarantee a fail-safe iterator on concurrent modification. The fail-safe or fail-fast behavior totally depends on the backing set.
4. Choosing between ConcurrentSkipListSet and Collections.SynchronizedSet()
As we have seen, ConcurrentSkipListSet and Collections.SynchronizedSet() are both useful methods to create a synchronized or thread-safe set in Java. Here are some general recommendations on how to choose between them:
- If you need to create a synchronized set that can be accessed concurrently by multiple threads without blocking them, we should use
ConcurrentSkipListSet. - If you need to create a synchronized set that can be accessed safely by multiple threads with data consistency, we should use
SynchronizedSet(). - If you need to create a synchronized set that can meet our specific requirements, we can create our own implementation of
SetorNavigableSetinterface using appropriate synchronization techniques, such as locks, semaphores, or atomic variables.
That’s all about ConcurrentSkipListSet and Collections.SynchronizedSet() in Java.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)