skip to content

What do the Collections.synchronizedXxx wrappers provide, what are their limits, and when would you prefer the java.util.concurrent collections?

level: seniorimportance: should knowfreq 50%

answer

  1. synchronizedXxx = one shared lock, each call guarded
  2. call sequences (check-then-act) NOT atomic — lock externally
  3. must synchronize the whole iteration loop
  4. single lock => contention bottleneck
  5. prefer ConcurrentHashMap (CAS + bin locks) / CopyOnWriteArrayList

basics

~10 s

Collections.synchronizedList/Map wrap a collection so each single call runs under one lock. Iterating still needs manual locking, and one shared lock serializes every guarded call, so concurrent collections like ConcurrentHashMap usually scale better.

solid answer

~50 s

synchronizedList, synchronizedMap and synchronizedSet wrap an existing collection and run each ordinary method call under one mutex, the wrapper itself, so individual calls are atomic and thread-safe, provided all access goes through the wrapper. Two big caveats: first, a sequence of calls (check-then-act, like contains then add) is not atomic, so you must synchronize externally on the wrapper; a single call such as putIfAbsent or computeIfAbsent on synchronizedMap is atomic. Second, iterator() and stream() take no lock, so you must hold the wrapper's lock for the whole traversal, or risk non-deterministic behavior such as ConcurrentModificationException. Because every guarded call serializes on one lock, contended throughput suffers. The alternative is java.util.concurrent: ConcurrentHashMap reads without locking, CASes into empty bins and otherwise locks a single bin; CopyOnWriteArrayList gives lock-free reads for read-heavy lists. Prefer these for real concurrency.

code

java · 13 lines
java
List<String> safe = Collections.synchronizedList(new ArrayList<>());

// Iteration MUST be guarded by the wrapper's own lock:
synchronized (safe) {
    for (String s : safe) {
        process(s);
    }
}

// Compound action also needs external locking:
synchronized (safe) {
    if (!safe.contains("x")) safe.add("x");
}

go deeper

for a junior

Knows synchronizedList/Map make a collection usable from multiple threads for single operations.

for a middle

Knows individual calls are atomic but iteration needs external synchronization to avoid ConcurrentModificationException.

for a senior

Explains multi-call races, the single-lock scalability limit, and reaches for ConcurrentHashMap/CopyOnWriteArrayList instead.

for a principal

Weighs per-bin locking vs copy-on-write vs single-mutex tradeoffs, weak consistency semantics, and sets guidance to avoid synchronized wrappers in new code.

## The job of the synchronized wrappers Most standard collections (`ArrayList`, `HashMap`, `HashSet`) are **not thread-safe** — concurrent access with at least one writing thread can corrupt them. `Collections.synchronizedList(list)`, `synchronizedMap(map)`, and `synchronizedSet(set)` (plus the `Collection`, sorted and navigable variants; JDK 27 has no sequenced one) return a wrapper whose methods run under a **single lock (mutex)**, the wrapper object itself. So one call like `add` or `get` is atomic relative to other calls — no two threads run a guarded method at the same time. ```java List<String> safe = Collections.synchronizedList(new ArrayList<>()); safe.add("x"); // each individual call is thread-safe ``` The guarantee holds only if **all access goes through the wrapper**. The Javadoc calls that critical: code that still touches the backing `ArrayList` directly bypasses the lock. ## Caveat 1: a sequence of calls is NOT atomic Thread safety applies only to **single** method calls. A **check-then-act** sequence spans two calls and is a race: ```java if (!safe.contains("x")) { // call 1 safe.add("x"); // call 2 — another thread may have added "x" in between } ``` Between the two calls another thread can interfere. To make the sequence atomic you must **synchronize externally on the wrapper object** (which is the same mutex the wrapper uses internally): ```java synchronized (safe) { if (!safe.contains("x")) safe.add("x"); } ``` A single compound *method* is a different case. `synchronizedMap` runs `putIfAbsent`, `computeIfAbsent`, `compute` and `merge` under the same mutex, so each is atomic. The cost is that the lock stays held while your function runs, and other guarded calls wait. ## Caveat 2: traversal must be manually synchronized `iterator()`, `listIterator()`, `spliterator()`, `stream()` and `parallelStream()` take **no lock**: `iterator()` simply returns the backing collection's iterator, so `hasNext` and `next` run unguarded. Another thread can mutate mid-iteration, which the Javadoc calls non-deterministic behavior; over an `ArrayList` it may surface as a `ConcurrentModificationException`. You must guard the entire iteration yourself: ```java synchronized (safe) { for (String s : safe) { ... } // hold the lock for the full loop } ``` This is a famous footgun — people assume "synchronized" means "safe to iterate," and it does not. Two details an interviewer may probe: - `safe.forEach(...)` and `safe.removeIf(...)` are ordinary guarded calls that hold the lock throughout, so they need no outer block. - For `synchronizedMap`, lock the **map**, not the view: `Set s = m.keySet();` can sit outside the block, but the iterator must be used inside `synchronized (m)`. ## Caveat 3: one lock = poor scalability Because **every** guarded operation contends for the **same single lock**, threads serialize: only one can run a guarded call at a time, even pure readers. Under load this becomes a bottleneck. One old penalty has gone: JEP 491 (JDK 24) eliminated nearly all cases of a virtual thread pinning its carrier while blocked in `synchronized`. At JDK 25 and 27 the wrappers still serialize; they just rarely tie up a carrier while doing it. ## The alternative: java.util.concurrent - **`ConcurrentHashMap`** — retrievals take no lock. An insert into an empty bin is a single **CAS**, and other updates lock only the first node of the affected bin with `synchronized`, so many threads operate concurrently. (Lock striping across `Segment`s was a previous design; the source keeps a stub `Segment` class only for serialization compatibility.) It exposes **atomic compound operations** (`putIfAbsent`, `computeIfAbsent`, `merge`) with no map-wide lock. Its iterators are *weakly consistent* — they never throw `ConcurrentModificationException` and tolerate concurrent updates. Unlike `synchronizedMap(new HashMap<>())`, it rejects `null` keys and values. - **`CopyOnWriteArrayList` / `CopyOnWriteArraySet`** — every write copies the whole backing array, so reads are lock-free and iterators see a stable snapshot. Excellent for read-heavy, write-rare lists (e.g. event listeners); expensive for write-heavy use. - **`ConcurrentLinkedQueue`, `BlockingQueue` implementations** — for producer/consumer patterns. ## When to use what - **Synchronized wrappers:** legacy code, trivial low-contention cases where you'll also handle iteration and multi-call locking, or when you need what the backing class gives, such as `LinkedHashMap` order or `null` values. Usually not the first choice for new code. - **ConcurrentHashMap:** the default for concurrent maps — better throughput under contention and atomic compound ops. - **CopyOnWriteArrayList:** read-mostly lists where writes are rare. ## Key terms - **Thread-safe:** behaves correctly when accessed by multiple threads simultaneously. - **Mutex / lock:** a guard ensuring only one thread enters a critical section at a time. - **Atomic operation:** appears to happen all-at-once; no other thread sees a half-done state. - **Compound / check-then-act:** an operation made of multiple steps that together must be atomic. - **CAS (compare-and-swap):** an atomic update that succeeds only if the value is still the one expected. - **Weakly consistent iterator:** an iterator that reflects some state at/after creation, never throws CME, but may not see the latest updates. - **ConcurrentModificationException:** thrown by fail-fast iterators when the collection is structurally modified during iteration.

  • Why must you synchronize manually when iterating a synchronizedList?
    The wrapper's iterator() returns the backing list's iterator with no lock, so hasNext and next run unguarded and another thread can mutate between them, which an ArrayList iterator may report as ConcurrentModificationException. You must hold the wrapper's lock for the entire loop.
  • How does ConcurrentHashMap avoid the single-lock bottleneck?
    Retrievals take no lock. An insert into an empty bin is a CAS, and other updates synchronize only on that bin's first node, so threads working in different bins rarely meet. Its iterators are weakly consistent and never throw CME.
  • Is computeIfAbsent on a synchronizedMap atomic?
    Yes. The wrapper runs it under the same mutex, so the whole call is atomic. The catch is scalability: the lock is held while your function runs, so other guarded calls on the map wait.

  • Believing iteration over a synchronized collection is automatically safe
  • Assuming check-then-act is atomic on a synchronized wrapper
  • Treating synchronizedMap as equivalent in throughput to ConcurrentHashMap
  • Using CopyOnWriteArrayList for write-heavy workloads
  • Thinking each hasNext and next on a synchronized list's iterator takes the lock
  • Describing today's ConcurrentHashMap as lock-striped with segments

Collections.synchronizedXxx wrappers
Java 1.2
ConcurrentHashMap
Java 1.5
CopyOnWriteArrayList
Java 1.5

Assumes JDK 27, the same at JDK 25 for everything here. ConcurrentHashMap's CAS and per-bin locking is its current design, not the older Segment striping; JEP 491 ended nearly all virtual-thread pinning on synchronized in JDK 24.

context