Java Collections synchronizedSortedSet() Method

Beginner
5 min read
Updated: Nov 2026
3 examples
java.util.Collections

Definition

In Java, Collections.synchronizedSortedSet(s) returns a thread-safe SortedSet wrapper. Besides the usual set methods, first(), last(), and the range views headSet, tailSet, and subSet are covered.

Range views share the parent's lock. When you loop over one, synchronize on the original wrapper, not on the range view.

A static method of the java.util.Collections utility class, available since Java 1.2. Call it on the class name, as in Collections.synchronizedSortedSet(...), after import java.util.Collections;. You never create a Collections object.

Syntax

Wrap a new TreeSet.

Java
SortedSet<Integer> queue = Collections.synchronizedSortedSet(new TreeSet<Integer>());
SortedSet<Integer> low = queue.headSet(10);
synchronized (queue) {          // lock the parent, even for the head view
    for (int x : low) { /* ... */ }
}
CallWhat it does
first() / last()Atomic reads of the ends.
headSet / tailSet / subSetViews guarded by the same lock.
synchronized (set) { first(); remove(); }Atomic "take the smallest".
ConcurrentSkipListSetA concurrent sorted set from java.util.concurrent.

Available since Java 1.2. For ceiling, floor, and pollFirst, use synchronizedNavigableSet (Java 8).

Library declarations
Java
// java.util.Collections
public static <T> SortedSet<T> synchronizedSortedSet(SortedSet<T> s)

Parameters

ParameterDescription
sThe sorted set to make thread-safe. Do not use it directly afterwards.

Return Value

Return ValueDescription
SortedSet<T>A synchronized view of s.

Compare with Similar Methods

Related wrappers:

MethodHow it differs
synchronizedNavigableSet(s)Adds atomic pollFirst and navigation.
synchronizedSet(s)Plain set; no first/last.
unmodifiableSortedSet(s)Read-only sorted view.

Java Examples

Example 1 — Evens and Odds from Two Threads

Two threads fill a sorted set; afterwards the ends and size are exact.

Java
import java.util.Collections;
import java.util.SortedSet;
import java.util.TreeSet;

public class CollectionsSynchronizedSortedSetEnds {
    public static void main(String[] args) throws InterruptedException {
        SortedSet<Integer> nums = Collections.synchronizedSortedSet(new TreeSet<Integer>());
        Thread evens = new Thread(() -> {
            for (int i = 2; i <= 100; i += 2) {
                nums.add(i);
            }
        });
        Thread odds = new Thread(() -> {
            for (int i = 1; i < 100; i += 2) {
                nums.add(i);
            }
        });
        evens.start();
        odds.start();
        evens.join();
        odds.join();
        System.out.println("size " + nums.size() + ", first " + nums.first() + ", last " + nums.last());
    }
}

How It Works

  1. Split work. One thread adds the even numbers 2-100, the other the odd numbers 1-99.
  2. Sorted on insert. The TreeSet places every number in order, and the lock keeps the tree intact.
  3. Exact ends. After both joins, first() is 1, last() is 100, and all 100 numbers are present.

Example 2 — Loop Over a headSet Safely

List the cold days from a headSet view, locking the original set, then watch the view update.

Java
import java.util.Arrays;
import java.util.Collections;
import java.util.SortedSet;
import java.util.TreeSet;

public class CollectionsSynchronizedSortedSetRange {
    public static void main(String[] args) {
        SortedSet<Integer> temps = Collections.synchronizedSortedSet(
            new TreeSet<>(Arrays.asList(12, 18, 25, 31, 7)));
        SortedSet<Integer> cold = temps.headSet(15);

        StringBuilder sb = new StringBuilder();
        synchronized (temps) {
            for (int t : cold) {
                sb.append(t).append(' ');
            }
        }
        System.out.println("cold days: " + sb.toString().trim());

        temps.add(3);
        System.out.println("cold view now: " + cold);
    }
}

How It Works

  1. Range view. headSet(15) covers temperatures below 15: 7 and 12.
  2. Which lock? The view uses the parent's lock, so the loop synchronizes on temps, as the JDK documentation requires.
  3. Live view. Adding 3 to the full set makes it appear in cold too.

Example 3 — Two Clerks Serving Tickets in Order

first() then remove() must happen as one step, or two clerks could serve the same ticket.

Java
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.SortedSet;
import java.util.TreeSet;

public class CollectionsSynchronizedSortedSetTake {
    public static void main(String[] args) throws InterruptedException {
        SortedSet<Integer> queue = Collections.synchronizedSortedSet(new TreeSet<Integer>());
        for (int i = 1; i <= 50; i++) {
            queue.add(i);
        }
        List<Integer> served = Collections.synchronizedList(new ArrayList<Integer>());
        Runnable clerk = () -> {
            while (true) {
                Integer next;
                synchronized (queue) {
                    if (queue.isEmpty()) {
                        return;
                    }
                    next = queue.first();
                    queue.remove(next);
                }
                served.add(next);
            }
        };
        Thread a = new Thread(clerk);
        Thread b = new Thread(clerk);
        a.start();
        b.start();
        a.join();
        b.join();
        System.out.println("served " + served.size() + ", distinct " + new TreeSet<>(served).size() + ", left " + queue.size());
    }
}

How It Works

  1. Three calls, one lock. isEmpty, first, and remove all run inside one synchronized (queue) block.
  2. No double service. Because no clerk can grab a ticket between another clerk's read and remove, each ticket is served once: 50 served, 50 distinct.
  3. Queue drained. Each clerk returns when the set is empty, leaving 0 tickets. How the 50 are split between clerks varies, so it is not printed.

Frequently Asked Questions

It returns a thread-safe SortedSet wrapper covering first, last, and the range views.
The original synchronized sorted set, not the headSet view.
No. Put both calls in one synchronized (set) block, or use synchronizedNavigableSet with pollFirst().
Yes. headSet, tailSet, and subSet views use the same lock as the parent.
java.util.concurrent.ConcurrentSkipListSet is a sorted set designed for concurrent use without a single global lock.

Next: unmodifiableCollection()

Wrap any Collection in a read-only view.

unmodifiableCollection() tutorial →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

13 people found this page helpful