C

Core Java tutorial for beginners

Clean • Professional

ConcurrentSkipListSet in Java – Thread-Safe Sorted Set with Examples

4 minute

ConcurrentSkipListSet in Java

ConcurrentSkipListSet is a high-performance, thread-safe, sorted Set in Java.

It belongs to the java.util.concurrent package and is built on Skip List data structure.

It is the concurrent alternative to TreeSet, offering better scalability, lock-free reads, and sorted ordering of elements.


What is ConcurrentSkipListSet?

A ConcurrentSkipListSet is a:

  • Thread-safe Sorted Set
  • Non-blocking (uses lock-free algorithms for most operations)
  • Duplicate-free collection (like all Sets)
  • Navigable Set (supports higher(), lower(), ceiling(), floor(), etc.)
  • Based on Skip List (multi-level linked structure)

It maintains elements in ascending natural order, unless you provide a custom Comparator.


Why Use ConcurrentSkipListSet?

Use it when you need:

  • A sorted Set that works safely in multi-threaded environments
  • Better concurrency than Collections.synchronizedSet()
  • Fast reads and moderate writes
  • A scalable alternative to TreeSet for concurrent apps
  • Support for NavigableSet operations

It is widely used in:

  • Real-time data processing
  • Caching systems
  • Ordered event processing
  • Concurrent analytics

Features of ConcurrentSkipListSet

FeatureDescription
Thread-safeSafe for multi-threaded access
SortedAlways stores elements in ascending order
Non-blockingUses CAS (Compare-And-Swap)
Duplicate-freeOnly unique elements allowed
NavigableSupports navigation methods
EfficientPerforms well under heavy concurrency

Internal Working

Internally, ConcurrentSkipListSet is backed by a:

ConcurrentSkipListMap

  • Keys = set elements
  • Values = dummy objects

And the map is implemented using a Skip List, which provides:

  • O(log n) insertion
  • O(log n) deletion
  • O(log n) search

Common Constructors

ConcurrentSkipListSet<Integer> set = new ConcurrentSkipListSet<>();
ConcurrentSkipListSet<String> set2 = new ConcurrentSkipListSet<>(Comparator.reverseOrder());

Common Methods

Since ConcurrentSkipListSet implements NavigableSet, SortedSet, and Set, it contains all important methods from these interfaces.

1. Basic Set Operations

MethodDescription
add(E e)Adds an element (sorted automatically).
remove(Object o)Removes the element if it exists.
contains(Object o)Checks if an element exists in the set.
size()Returns number of elements.
isEmpty()Checks if set is empty.
clear()Removes all elements.

2. Navigation Methods (From NavigableSet)

These methods help you find elements relative to a given value.

MethodMeaning
higher(E e)Returns the next higher element (strictly > e).
lower(E e)Returns the next lower element (strictly < e).
ceiling(E e)Returns element ≥ e.
floor(E e)Returns element ≤ e.
first()Smallest element.
last()Largest element.

3. Range Views (Subsets)

These return live views of parts of the set.

MethodDescription
subSet(E from, E to)Returns elements from from (inclusive) to to (exclusive).
headSet(E to)Returns elements less than to.
tailSet(E from)Returns elements ≥ from.
descendingSet()Returns elements in reverse (descending) order.

4. Iterator Methods

MethodDescription
iterator()Returns ascending order iterator.
descendingIterator()Returns reverse order iterator.

Note: Iterators are weakly consistent, meaning they:

  • Do not throw ConcurrentModificationException
  • Reflect some (but not necessarily all) recent updates

5. Bulk Operations

MethodDescription
addAll(Collection c)Adds all elements from another collection.
removeAll(Collection c)Removes all matching elements.
retainAll(Collection c)Keeps only elements present in the given collection.

Simple Example

import java.util.concurrent.*;

public class Demo {
    public static void main(String[] args) {
        ConcurrentSkipListSet<Integer> set = new ConcurrentSkipListSet<>();

        set.add(20);
        set.add(10);
        set.add(30);

        System.out.println(set);   // [10, 20, 30]

        System.out.println(set.higher(20)); // 30
        System.out.println(set.lower(20));  // 10

        set.remove(20);
        System.out.println(set);   // [10, 30]
    }
}

Thread-Safety Example

ConcurrentSkipListSet<Integer> set = new ConcurrentSkipListSet<>();

Runnable task = () -> {
    for (int i = 1; i <= 5; i++) {
        set.add(i);
    }
};

Thread t1 = new Thread(task);
Thread t2 = new Thread(task);

t1.start();
t2.start();
  • No synchronization needed
  • No ConcurrentModificationException

When NOT to Use It

Avoid it if:

  • You do not need sorting
  • You need extremely fast writes → use ConcurrentHashMap / ConcurrentSkipListMap
  • You only need random insertion + high performance → use ConcurrentHashMap KeySet

Advantages

  • Highly concurrent
  • Lock-free reads
  • Predictable ordering
  • Fail-safe iterator
  • Better scaling under load

Disadvantages

  • Slower writes compared to non-thread-safe Sets
  • More memory consumption due to Skip List levels
  • Ordering cost → slower than HashSet

Difference Between ConcurrentSkipListSet & TreeSet

FeatureConcurrentSkipListSetTreeSet
Thread SafetyThread-safe (supports concurrent access)Not thread-safe
Internal Data StructureSkip ListRed-Black Tree
Performance Under ConcurrencyExcellent – non-blocking, scalablePoor – must be externally synchronized
Iterator TypeWeakly consistent (never fails)Fail-fast (throws ConcurrentModificationException)
Order of ElementsSorted (natural or custom comparator)Sorted (natural or custom)
Concurrent ReadsMultiple threads can read simultaneouslyUnsafe without sync
Concurrent WritesSupported with minimal lockingUnsafe without sync
Time Complexity (add, remove, search)O(log n)O(log n)
Use CasesMulti-threaded, high-concurrency appsSingle-threaded or low-concurrency apps
Packagejava.util.concurrentjava.util
NavigableSet SupportYesYes
Null ElementsNot allowedNot allowed
Memory UsageSlightly higher due to skip-list levelsLess memory compared to skip-list

Use Cases

  • Real-time leaderboards
  • Sorted user sessions
  • Time-ordered tasks
  • Multi-threaded filtering & ranking
  • Message processing systems

Article 0 of 0