Skip to main content
ConcurrentHashMap · Topic 6 of 6

synchronizedMap vs ConcurrentHashMap

Definition​

Collections.synchronizedMap wraps any map with one lock, so only one thread works at a time and you must still lock by hand when you loop or combine steps. ConcurrentHashMap locks only a small part and has atomic methods, so it scales much better.

Example code​

The extra locking a synchronized map needs

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

class Demo {
public static void main(String[] args) {
Map<String, Integer> synced = Collections.synchronizedMap(new HashMap<>());
synced.put("a", 1);
synced.put("b", 2);

// each call is safe, but looping needs you to hold the map's lock yourself
synchronized (synced) {
for (Map.Entry<String, Integer> entry : synced.entrySet()) {
System.out.println(entry.getKey() + "=" + entry.getValue());
}
}

// check-then-act also needs the lock with a synchronized map...
synchronized (synced) {
if (!synced.containsKey("c")) synced.put("c", 3);
}

// ...but is one atomic call with ConcurrentHashMap
Map<String, Integer> concurrent = new ConcurrentHashMap<>(synced);
concurrent.putIfAbsent("d", 4);
System.out.println(new java.util.TreeMap<>(concurrent));
}
}

// Output:
// a=1
// b=2
// {a=1, b=2, c=3, d=4}

Finished this page? Track your progress (saved only in your browser).