Java Collections synchronizedSortedMap() Method

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

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.

Java
SortedMap<Integer, String> events = Collections.synchronizedSortedMap(new TreeMap<Integer, String>());
events.put(5, "login");
synchronized (events) {
    for (int t : events.tailMap(3).keySet()) { /* ... */ }
}
CallWhat 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
// java.util.Collections
public static <K,V> SortedMap<K,V> synchronizedSortedMap(SortedMap<K,V> m)

Parameters

ParameterDescription
mThe sorted map to make thread-safe. Do not use it directly afterwards.

Return Value

Return ValueDescription
SortedMap<K,V>A synchronized view of m.

Compare with Similar Methods

Related wrappers:

MethodHow it differs
synchronizedNavigableMap(m)Adds navigation and atomic polling.
synchronizedMap(m)Any map; no ordering methods.
unmodifiableSortedMap(m)Read-only sorted view.

Java Examples

Example 1 — Events from Two Sources

A web thread logs even timestamps, an app thread logs odd ones. The sorted map interleaves them correctly.

Java
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());
    }
}

How It Works

  1. Distinct keys. The threads never write the same timestamp, so every put adds a new entry.
  2. Tree kept consistent. The lock ensures the TreeMap is never rebalanced by two threads at once.
  3. 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.

Java
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);
    }
}

How It Works

  1. Sortable keys. "yyyy-MM" strings sort in date order, so tailMap("2026-03") means March onwards.
  2. Parent lock. Looping over fromMarch.values() takes many calls, so the loop holds synchronized (prices).
  3. 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.

Java
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);
    }
}

How It Works

  1. Compound update. put, size, and remove(firstKey()) run together inside synchronized (top).
  2. 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.
  3. 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

It returns a thread-safe SortedMap wrapper covering firstKey, lastKey, and range views.
Hold synchronized (originalWrapper) around the loop; sub-maps share the parent's lock.
No. Put both inside one synchronized (map) block, as in the leaderboard example.
The navigable version (Java 8) also offers floorEntry, ceilingKey, pollFirstEntry, and descending views.
java.util.concurrent.ConcurrentSkipListMap is a sorted map built for concurrent access.

Next: synchronizedSortedSet()

Wrap a SortedSet so each call, including range views, is thread-safe.

synchronizedSortedSet() 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.

12 people found this page helpful