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()) { /* ... */ }
}
Call
What it does
get / put / remove
Each call is atomic.
merge / compute / putIfAbsent
Java 8 compound methods, also atomic.
synchronized (map) { for keySet... }
Iteration over any view needs the map's lock.
ConcurrentHashMap
Alternative 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
Parameter
Description
m
The map to make thread-safe. Do not use it directly afterwards.
Atomic claim.putIfAbsent checks and stores under the lock; only the first caller sees null.
Losers informed. The other two threads get the existing leader's name back and do nothing.
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.