All 15 Collections Framework questions
More in Collections Framework
Advertisement
Java › Collections Framework

What is the purpose of the Collections utility class's synchronization wrappers (Collections.synchronizedList(), etc.), and how do they differ from genuinely concurrent collections like ConcurrentHashMap?

Intermediate

Answer

Collections.synchronizedList()/synchronizedMap()/etc. wrap a regular collection so every individual method call is synchronized on a common lock, providing basic thread safety for individual operations -- but critically, compound operations (like check-then-act patterns, or iteration) still require the caller to manually synchronize on the wrapper externally to be safe, since iteration isn't itself atomic even though each individual method call is; ConcurrentHashMap and similar java.util.concurrent collections instead provide much finer-grained, lock-striped or lock-free internal synchronization designed specifically for safe concurrent access without requiring external synchronization even for iteration, and are generally strongly preferred over the legacy synchronized wrappers for genuinely concurrent workloads.
List<String> syncList = Collections.synchronizedList(new ArrayList<>());

// Individual calls are safe:
syncList.add("item");

// But iteration STILL requires external synchronization, or ConcurrentModificationException risk remains:
synchronized (syncList) {
    for (String s : syncList) { System.out.println(s); }
}

// ConcurrentHashMap needs no such external synchronization for safe iteration
Map<String, Integer> concurrentMap = new ConcurrentHashMap<>();
Real-world example A team using Collections.synchronizedMap() but forgetting the requirement to externally synchronize during iteration experiences an intermittent ConcurrentModificationException under load, resolved by migrating to ConcurrentHashMap, which handles concurrent iteration safely without requiring this easy-to-miss external synchronization discipline.

Common follow-ups: Why does synchronizing individual method calls not make iteration automatically safe as well?;What specific concurrency techniques does ConcurrentHashMap use internally to avoid needing a single global lock?