Java Collections synchronizedMap() Method

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

Definition

In Java, Collections.synchronizedMap(m) returns a Map wrapper in which every method holds the same lock. That includes Java 8 methods such as merge, compute, and putIfAbsent, so each of those is atomic too.

Iterating over keySet(), values(), or entrySet() is not automatic: you must hold synchronized (map), locking the map wrapper, not the 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.synchronizedMap(...), after import java.util.Collections;. You never create a Collections object.

Syntax

Wrap a new map and share the wrapper.

Java
Map<String, Integer> counts = Collections.synchronizedMap(new TreeMap<String, Integer>());
counts.merge(word, 1, Integer::sum);    // atomic
synchronized (counts) {                 // lock the map to iterate its views
    for (String k : counts.keySet()) { /* ... */ }
}
CallWhat it does
get / put / removeEach call is atomic.
merge / compute / putIfAbsentJava 8 compound methods, also atomic.
synchronized (map) { for keySet... }Iteration over any view needs the map's lock.
ConcurrentHashMapAlternative with finer-grained locking and lock-free reads.

Available since Java 1.2. A single lock for the whole map is simple but can become a bottleneck with many threads; ConcurrentHashMap is usually faster under heavy load.

Library declarations
Java
// java.util.Collections
public static <K,V> Map<K,V> synchronizedMap(Map<K,V> m)

Parameters

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

Return Value

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

Compare with Similar Methods

Related wrappers:

MethodHow it differs
synchronizedSortedMap(m)Keeps firstKey and range views.
unmodifiableMap(m)Read-only map view.
checkedMap(m, k, v)Rejects keys or values of the wrong type.

Java Examples

Example 1 — Two Threads Counting Words with merge

Each thread counts its own half of the words into one shared map.

Java
import java.util.Collections;
import java.util.Map;
import java.util.TreeMap;

public class CollectionsSynchronizedMapCounts {
    public static void main(String[] args) throws InterruptedException {
        Map<String, Integer> counts = Collections.synchronizedMap(new TreeMap<String, Integer>());
        String[] partA = {"red", "blue", "red"};
        String[] partB = {"blue", "red", "green"};

        Thread a = new Thread(() -> {
            for (String w : partA) {
                counts.merge(w, 1, Integer::sum);
            }
        });
        Thread b = new Thread(() -> {
            for (String w : partB) {
                counts.merge(w, 1, Integer::sum);
            }
        });
        a.start();
        b.start();
        a.join();
        b.join();
        System.out.println(counts);
    }
}

How It Works

  1. Read-modify-write. merge reads the old count, adds 1, and stores it; the wrapper does all of that under one lock.
  2. No lost updates. Both threads bump "red" and "blue", yet no increment is lost: red reaches 3 and blue 2.
  3. Stable output. The backing TreeMap prints keys alphabetically, whatever order the threads ran in.

Example 2 — Scan the Keys While Holding the Map's Lock

Find out-of-stock items by looping over keySet(), and total the stock from values().

Java
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

public class CollectionsSynchronizedMapIterate {
    public static void main(String[] args) {
        Map<String, Integer> stock = Collections.synchronizedMap(new TreeMap<String, Integer>());
        stock.put("apple", 3);
        stock.put("pear", 0);
        stock.put("plum", 7);

        List<String> empty = new ArrayList<>();
        int total = 0;
        synchronized (stock) {
            for (String k : stock.keySet()) {
                if (stock.get(k) == 0) {
                    empty.add(k);
                }
            }
            for (int v : stock.values()) {
                total += v;
            }
        }
        System.out.println("out of stock: " + empty + ", total units: " + total);
    }
}

How It Works

  1. Views share the lock. keySet() and values() are views guarded by the map wrapper's lock, so the block synchronizes on stock itself.
  2. Nested calls are fine. stock.get(k) inside the block takes the same lock again; Java locks are reentrant, so this does not deadlock.
  3. Consistent results. Both scans see the same state: pear is empty and 3 + 0 + 7 = 10 units.

Example 3 — Exactly One Thread Becomes Leader

Three threads call putIfAbsent("leader", name). The one that gets null back is the winner.

Java
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

public class CollectionsSynchronizedMapLeader {
    public static void main(String[] args) throws InterruptedException {
        Map<String, String> roles = Collections.synchronizedMap(new TreeMap<String, String>());
        List<String> winners = Collections.synchronizedList(new ArrayList<String>());
        List<Thread> threads = new ArrayList<>();

        for (String name : Arrays.asList("ana", "ben", "cy")) {
            Thread t = new Thread(() -> {
                if (roles.putIfAbsent("leader", name) == null) {
                    winners.add(name);
                }
            });
            threads.add(t);
            t.start();
        }
        for (Thread t : threads) {
            t.join();
        }
        System.out.println("winners: " + winners.size() + ", map size: " + roles.size());
        System.out.println("leader matches winner? " + roles.get("leader").equals(winners.get(0)));
    }
}

How It Works

  1. Atomic claim. putIfAbsent checks and stores under the lock; only the first caller sees null.
  2. Losers informed. The other two threads get the existing leader's name back and do nothing.
  3. Print facts, not names. Which thread wins changes from run to run, so the program prints the counts and confirms the stored leader is the recorded winner.

Frequently Asked Questions

It returns a Map wrapper whose methods all hold one lock, making each call thread-safe.
Hold synchronized (map) around the loop, locking the map wrapper itself rather than its keySet or entrySet view.
Yes. In Java 8+ the wrapper runs them while holding its lock.
ConcurrentHashMap usually performs better with many threads and iterates without locking; synchronizedMap can wrap any map, such as a TreeMap.
It follows the wrapped map. A HashMap allows one null key; a TreeMap with natural ordering does not.

Next: synchronizedNavigableMap()

Wrap a NavigableMap so floorEntry, pollFirstEntry, and views are thread-safe.

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

8 people found this page helpful