Home Java Collections Methods synchronizedSortedMap() Java Collections synchronizedSortedMap() Method Definition In Java, Collections.synchronizedSortedMap(m) returns a thread-safe SortedMap wrapper. It locks the usual map methods plus firstKey(), lastKey(), and the range views headMap, tailMap, and subMap.
As with the other synchronized wrappers, loops over the map, its views, or its sub-maps must hold synchronized (wrapper) on the original wrapper.
A static method of the java.util.Collections utility class, available since Java 1.2. Call it on the class name, as in Collections.synchronizedSortedMap(...), after import java.util.Collections;. You never create a Collections object.
Syntax Wrap a new TreeMap.
SortedMap<Integer, String> events = Collections.synchronizedSortedMap(new TreeMap<Integer, String>());
events.put(5, "login");
synchronized (events) {
for (int t : events.tailMap(3).keySet()) { /* ... */ }
} Call What it does firstKey() / lastKey()Atomic reads of the smallest / largest key. headMap / tailMap / subMapSub-maps guarded by the parent's lock. synchronized (map) { put; if too big remove }Compound updates in one step. ConcurrentSkipListMapConcurrent sorted map from java.util.concurrent.
Available since Java 1.2. For floorEntry, pollFirstEntry, and descending views use synchronizedNavigableMap (Java 8).
Library declarations // java.util.Collections
public static <K,V> SortedMap<K,V> synchronizedSortedMap(SortedMap<K,V> m) Parameters Parameter Description mThe sorted map to make thread-safe. Do not use it directly afterwards.
Return Value Return Value Description SortedMap<K,V>A synchronized view of m.
Important
Iterating any key, value, entry, or sub-map view requires synchronized (wrapper); without it, ConcurrentModificationException is possible. firstKey() and lastKey() throw NoSuchElementException if the map is empty.
Compare with Similar Methods Related wrappers:
Java Examples 1. Concurrent puts 2. Lock for sub-maps 3. Top-3 board Example 1 — Events from Two Sources A web thread logs even timestamps, an app thread logs odd ones. The sorted map interleaves them correctly.
import java.util.Collections;
import java.util.SortedMap;
import java.util.TreeMap;
public class CollectionsSynchronizedSortedMapEvents {
public static void main(String[] args) throws InterruptedException {
SortedMap<Integer, String> events = Collections.synchronizedSortedMap(new TreeMap<Integer, String>());
Thread web = new Thread(() -> {
for (int t = 0; t < 10; t += 2) {
events.put(t, "web");
}
});
Thread app = new Thread(() -> {
for (int t = 1; t < 10; t += 2) {
events.put(t, "app");
}
});
web.start();
app.start();
web.join();
app.join();
int first = events.firstKey();
int last = events.lastKey();
System.out.println("first " + first + "=" + events.get(first) + ", last " + last + "=" + events.get(last));
System.out.println("size " + events.size());
}
} first 0=web, last 9=app
size 10 How It Works Distinct keys. The threads never write the same timestamp, so every put adds a new entry.Tree kept consistent. The lock ensures the TreeMap is never rebalanced by two threads at once.Ordered result. Timestamp 0 came from the web thread and 9 from the app thread; all 10 events are stored.Example 2 — Maximum Price Since March Loop over a tailMap view while holding the parent map's lock.
import java.util.Collections;
import java.util.SortedMap;
import java.util.TreeMap;
public class CollectionsSynchronizedSortedMapTail {
public static void main(String[] args) {
SortedMap<String, Integer> prices = Collections.synchronizedSortedMap(new TreeMap<String, Integer>());
prices.put("2026-01", 10);
prices.put("2026-02", 12);
prices.put("2026-03", 9);
prices.put("2026-04", 15);
SortedMap<String, Integer> fromMarch = prices.tailMap("2026-03");
int max = 0;
synchronized (prices) {
for (int p : fromMarch.values()) {
max = Math.max(max, p);
}
}
System.out.println("since March: " + fromMarch + ", max " + max);
}
} since March: {2026-03=9, 2026-04=15}, max 15 How It Works Sortable keys. "yyyy-MM" strings sort in date order, so tailMap("2026-03") means March onwards.Parent lock. Looping over fromMarch.values() takes many calls, so the loop holds synchronized (prices).Result. Of 9 and 15, the highest price since March is 15.Example 3 — A Thread-Safe Top-3 Leaderboard Each new score is added and, if the board has more than three, the lowest is dropped, all as one locked step.
import java.util.Collections;
import java.util.SortedMap;
import java.util.TreeMap;
public class CollectionsSynchronizedSortedMapTop {
static void record(SortedMap<Integer, String> top, int score, String who) {
synchronized (top) {
top.put(score, who);
if (top.size() > 3) {
top.remove(top.firstKey());
}
}
}
public static void main(String[] args) throws InterruptedException {
SortedMap<Integer, String> top = Collections.synchronizedSortedMap(new TreeMap<Integer, String>());
Thread a = new Thread(() -> {
for (int s = 1; s <= 20; s += 2) {
record(top, s, "a");
}
});
Thread b = new Thread(() -> {
for (int s = 2; s <= 20; s += 2) {
record(top, s, "b");
}
});
a.start();
b.start();
a.join();
b.join();
System.out.println("top 3: " + top);
}
} top 3: {18=b, 19=a, 20=b} How It Works Compound update. put, size, and remove(firstKey()) run together inside synchronized (top).Always trimmed. A score is dropped only when three higher scores are on the board, so the board can never lose a true top-3 score.Same answer every run. Player a posts odd scores and b even ones; however the threads interleave, the final board is 18, 19, 20.Frequently Asked Questions What does Collections.synchronizedSortedMap() do? It returns a thread-safe SortedMap wrapper covering firstKey, lastKey, and range views.
How do I iterate a tailMap of a synchronizedSortedMap? Hold synchronized (originalWrapper) around the loop; sub-maps share the parent's lock.
Is put followed by remove(firstKey()) atomic? No. Put both inside one synchronized (map) block, as in the leaderboard example.
What is the difference from synchronizedNavigableMap()? The navigable version (Java 8) also offers floorEntry, ceilingKey, pollFirstEntry, and descending views.
What is a concurrent alternative? java.util.concurrent.ConcurrentSkipListMap is a sorted map built for concurrent access.
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.
12 people found this page helpful
Helpful Share Copy link Suggestion