CKTIS / Java
Collections.synchronizedMap: locking access and iteration
Wrap an existing map to synchronize individual method calls. When traversing a view, lock the returned map for the entire traversal, not the view itself.
Version: Java SE 21
Syntax
public static <K, V> Map<K, V> synchronizedMap(Map<K, V> m)Collections.synchronizedMap(m) is a static method on java.util.Collections. It returns a synchronized Map<K, V> wrapper, where K is the key type and V is the value type. The wrapper uses m as its backing map rather than copying it. To preserve synchronization, access the data only through the returned map and its views, never directly through m.
When traversing keySet(), values(), or entrySet() with an Iterator, Spliterator, or Stream, explicitly hold the returned map's monitor with synchronized (map). Do not lock the view or the backing map. You can obtain the view before the block, but create and use the iterator or spliterator inside it. For a sequential stream, run the terminal operation inside the block too. An enhanced for loop over a view also uses an iterator. Without this lock, traversal can behave nondeterministically.
Synchronizing individual methods does not make a sequence of calls atomic. If you call containsKey() and then call put() only when the key is absent, put both the check and the conditional write in one synchronized (map) block. Otherwise, another thread can change the map between the two calls.
Examples
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.Map;
public class Main {
public static void main(String[] args) {
Map<String, Integer> scores = Collections.synchronizedMap(new LinkedHashMap<>());
scores.put("Ada", 3);
scores.put("Lin", 5);
synchronized (scores) {
for (Map.Entry<String, Integer> entry : scores.entrySet()) {
System.out.println(entry.getKey() + "=" + entry.getValue());
}
}
}
}Result
Ada=3 Lin=5
The loop traverses `entrySet()` inside `synchronized (scores)`. The order `Ada=3`, then `Lin=5`, comes from `LinkedHashMap` insertion order, not synchronization. The example shows where to lock; it does not start additional threads.
Related lessons
- Java · Lesson 18 · Advanced · Version: 2