Skip to the page

Concurrency · mid

Thread-safe counters and maps

ConcurrentHashMap is safe per call, but get-then-put is not atomic. Use merge, computeIfAbsent, LongAdder or a lock for the whole action, and never run slow code inside them.

The notes

What you must know

  • Hashtable and synchronizedMap use one lock for every call. Java 7 ConcurrentHashMap used 16 segments. Java 8 and later use one table: CAS for an empty bucket, a lock on the first node for a non-empty bucket.
  • No nulls: get returning null must mean absent.
  • Check-then-act is not atomic. counts.put(m, counts.getOrDefault(m, 0) + 1) loses updates even in a ConcurrentHashMap. Use merge(m, 1L, Long::sum) or computeIfAbsent(m, k -> new LongAdder()).increment().
  • size() is an estimate under updates; mappingCount() returns a long. Iterators are weakly consistent and never throw ConcurrentModificationException.
  • computeIfAbsent and compute run your function while the bucket is locked. A slow function, such as a remote call, blocks other keys in the same bucket and can use up all request threads. Do not change the same map inside it.
  • Better for slow loads: Caffeine with an async loader, timeouts on the client, a fallback value and a bulkhead.
  • AtomicLong uses compare-and-swap in a retry loop. LongAdder spreads updates over cells and is much faster for hot counters. Its sum is not an exact snapshot during updates.
  • ReentrantLock over synchronized: tryLock with a timeout, interruptible waiting, fairness, several Conditions. Always unlock in finally. ReadWriteLock or StampedLock for read-heavy data. In-memory locks protect nothing across pods. The database must enforce it: a conditional UPDATE ... WHERE balance >= :amount, row locks or optimistic locking.

The red pen

Common traps: mistake → fix

  • Mistake: ConcurrentHashMap makes get-then-put safe

    Fix: each call is safe; the pair is not atomic.

  • Mistake: A flush that copies then clears is safe

    Fix: updates between copy and clear are lost; swap the map atomically.

  • Mistake: computeIfAbsent is a good place for a remote call

    Fix: it holds a bucket lock while it runs.

Easy to hard

Questions interviewers ask, easy to hard

  1. How does ConcurrentHashMap stay thread-safe without locking the whole map?
  2. Why does a ConcurrentHashMap counter still lose updates?
  3. AtomicLong or LongAdder for 200 threads counting API calls?
  4. Why did product pages hang when the pricing call became slow inside computeIfAbsent?

Your first interview is free

Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.

Start your free interview