Command Palette

Search for a command to run...

PHASE 5Advanced ~6 min· topic 3 of 11

Topic 5.3

Concurrent Data Structures / Atomics

In one line

AtomicInteger, AtomicLong, ConcurrentHashMap, BlockingQueue — the toolbox that removes most manual locking.

0/11 · 0%

Think of it like this

A shared Google Sheet where multiple people can edit different rows at the same time without a 'save conflict', because the sheet itself manages who is touching what.

Key ideas

  1. 01

    Atomic* classes: CAS-based; atomic increment without locks — the answer to 'how do I count without synchronized?'.

  2. 02

    ConcurrentHashMap: thread-safe map with per-bucket locks and lock-free reads; computeIfAbsent is atomic.

  3. 03

    BlockingQueue: the producer-consumer primitive — put() blocks when full, take() when empty.

  4. 04

    CopyOnWriteArrayList: read-heavy lists where writes are rare (listeners, small registries).

  5. 05

    The interview habit: 'I'll keep the free spots in a ConcurrentHashMap and claim with compute'.

Java / Spring map

  • →

    java.util.concurrent.* — all of the above; plus LongAdder for hot counters (contention-cheap).

Code & diagrams

ConcurrentCollections.javajava

The three workhorses: atomic counter, concurrent registry, blocking queue.

LongAdder requests = new LongAdder();      // best for hot counters
requests.increment();

Map<String, Seat> seats = new ConcurrentHashMap<>();
// atomic claim without a lock:
Seat claimed = seats.computeIfAbsent("A12", k -> new Seat("A12", SeatState.HELD));
if (claimed.state() != SeatState.HELD) throw new SeatTaken();

BlockingQueue<String> jobs = new ArrayBlockingQueue<>(10_000);
// producer thread pool:
jobs.put("render:order-" + orderId);        // blocks if full → back-pressure
// consumer thread pool:
String job = jobs.take();                    // blocks when empty → no busy-wait

Explain without notes

01

Why is ConcurrentHashMap.compute better than get-then-put for the seat claim?

Practice

01

Rewrite the TicketBookMyShow seat hold using computeIfAbsent and explain the race you eliminated.

Trade-offs

  • ↔

    ConcurrentHashMap trades memory for safety; BlockingQueue gives back-pressure at the cost of latency.

Completion checklist

  • I automatically reach for ConcurrentHashMap + atomics before writing a manual lock.

Back to phase