Home Java Collections Methods synchronizedSortedSet() Java Collections synchronizedSortedSet() Method 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.
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) { /* ... */ }
} Call What 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.util.Collections
public static <T> SortedSet<T> synchronizedSortedSet(SortedSet<T> s) Parameters Parameter Description sThe sorted set to make thread-safe. Do not use it directly afterwards.
Return Value Return Value Description SortedSet<T>A synchronized view of s.
Important
Iterating the set or any range view requires synchronized (wrapper) on the original wrapper, or a concurrent change may cause ConcurrentModificationException. "Read first(), then remove it" is two calls and must be locked together.
Compare with Similar Methods Related wrappers:
Java Examples 1. Concurrent ends 2. Lock the parent 3. Take smallest Example 1 — Evens and Odds from Two Threads Two threads fill a sorted set; afterwards the ends and size are exact.
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());
}
} size 100, first 1, last 100 How It Works Split work. One thread adds the even numbers 2-100, the other the odd numbers 1-99.Sorted on insert. The TreeSet places every number in order, and the lock keeps the tree intact.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.
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);
}
} cold days: 7 12
cold view now: [3, 7, 12] How It Works Range view. headSet(15) covers temperatures below 15: 7 and 12.Which lock? The view uses the parent's lock, so the loop synchronizes on temps, as the JDK documentation requires.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.
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());
}
} served 50, distinct 50, left 0 How It Works Three calls, one lock. isEmpty, first, and remove all run inside one synchronized (queue) block.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.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 What does Collections.synchronizedSortedSet() do? It returns a thread-safe SortedSet wrapper covering first, last, and the range views.
Which object do I lock when iterating headSet()? The original synchronized sorted set, not the headSet view.
Is first() followed by remove() atomic? No. Put both calls in one synchronized (set) block, or use synchronizedNavigableSet with pollFirst().
Are range views of the wrapper thread-safe? Yes. headSet, tailSet, and subSet views use the same lock as the parent.
What is a concurrent alternative? java.util.concurrent.ConcurrentSkipListSet is a sorted set designed for concurrent use without a single global lock.
About the author Developer, cloud engineer, and technical writer
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
Helpful Share Copy link Suggestion