Topic 5.3
Concurrent Data Structures / Atomics
In one line
AtomicInteger, AtomicLong, ConcurrentHashMap, BlockingQueue — the toolbox that removes most manual locking.
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
- 01
Atomic* classes: CAS-based; atomic increment without locks — the answer to 'how do I count without synchronized?'.
- 02
ConcurrentHashMap: thread-safe map with per-bucket locks and lock-free reads; computeIfAbsent is atomic.
- 03
BlockingQueue: the producer-consumer primitive — put() blocks when full, take() when empty.
- 04
CopyOnWriteArrayList: read-heavy lists where writes are rare (listeners, small registries).
- 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
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-waitExplain without notes
Why is ConcurrentHashMap.compute better than get-then-put for the seat claim?
Practice
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.